Reputation: 5742
Now I am trying to test it using JUnit4, but I am getting
java.lang.IllegalStateException:
Must not be called on the main application thread
at com.google.android.gms.common.internal.zzab.zzhj(Unknown Source)
at com.google.android.gms.common.internal.zzab.zzate(Unknown Source)
at com.google.android.gms.tasks.Tasks.await(Unknown Source)
at com.example.tasks.GetUserProfileTest.then(GetUserProfileTest.java:18)
<27 internal calls>
Process finished with exit code 255
I've created a Continuation task that performs an operation on Firebase Realtime Database.
public class GetUserProfile implements Continuation<String, Task<Profile>>,
ValueEventListener {
private TaskCompletionSource<Profile> mTaskCompletionSource;
private DatabaseReference mDatabase;
public GetUserProfile() {
mTaskCompletionSource = new TaskCompletionSource();
mDatabase = FirebaseDatabase.getInstance().getReference();
}
@Override
public void onCancelled(DatabaseError databaseError) {
mDatabase.removeEventListener(this);
mTaskCompletionSource.setException(databaseError.toException());
}
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mDatabase.removeEventListener(this);
mTaskCompletionSource.setResult(dataSnapshot.getValue(Profile.class));
}
@Override
public Task<Profile> then(Task<String> task) {
mDatabase.child(task.getResult()).addValueEventListener(this);
return mTaskCompletionSource.getTask();
}
}
and unit test for it:
public class GetUserProfileTest {
@Test
public void then() throws Exception {
Task<Profile> task = Tasks.<String>forResult("17354686546")
.continueWithTask(new GetUserProfile());
try {
Profile profile = Tasks.await(task);
assertEquals(profile.getEmail(), "[email protected]");
} catch (ExecutionException e) {
fail(e.getMessage());
} catch (InterruptedException e) {
fail(e.getMessage());
}
}
}
Is there a simple way of testing tasks without using handlers or CountDownLatch
?
Upvotes: 4
Views: 2876
Reputation: 5742
public class GetUserProfileTest {
@Test
public void then() throws Exception {
try {
Task<String> previousTask = Tasks.forResult("17354686546");
GetUserProfile continuation = new GetUserProfile();
Profile profile = continuation
.then(previousTask)
.getResult();
assertEquals(profile.getEmail(), "[email protected]");
} catch (ExecutionException e) {
fail(e.getMessage());
} catch (InterruptedException e) {
fail(e.getMessage());
}
}
}
Upvotes: 2