现在我正在尝试使用 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
?
最佳答案
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(), "john.connor@email.com");
} catch (ExecutionException e) {
fail(e.getMessage());
} catch (InterruptedException e) {
fail(e.getMessage());
}
}
}
关于android - 如何在 Android 上测试 Firebase 任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40656976/