现在我正在尝试使用JUnit4测试它,但我正在
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
我已经创建了一个Continuation任务,可以对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();
}
}
并对其进行单元测试:
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(), "john.connor@email.com");
} catch (ExecutionException e) {
fail(e.getMessage());
} catch (InterruptedException e) {
fail(e.getMessage());
}
}
}
是否有一种简单的方法可以在不使用handlers或CountDownLatch
的情况下测试任务?
答案 0 :(得分:0)
bluebird