Reputation: 55
I want to test the code below with Mockito
@Override
public void getSessionList(final int carId, final ResultCallback<List<Session>> callback) {
jobExecutor.execute(new Runnable() {
@Override
public void run() {
List<SessionEntity> sessions = IDataStore.getSessionList(carId);
final List<Session> sessionList = new ArrayList<>();
if (sessions != null) {
for (SessionEntity entity : sessions) {
sessionList.add(mapper.transform(entity));
}
uiThread.post(new Runnable() {
@Override
public void run() {
if (callback != null) {
callback.onResult(sessionList);
}
}
});
}
}
});
}
I tried to do something like this, but my verify methods will be executed early than runnable. Thread.sleep() works well for the first two verify, but how to test the result from callback.onResult which will be executed in the main thread?
private Repository repository // not mocked
@Mock
private IDataStore dataStore;
@Mock
private DataToDomainMapper dataToDomainMapper;
@Mock
private ResultCallback resultCallback;
@Test
public void testGetSessionListCallbackSuccess(){
List<SessionEntity> sessionEntities = Arrays.asList(sessionEntity, sessionEntity, sessionEntity);
given(dataStore.getSessionList(anyInt())).willReturn(sessionEntities);
given(dataToDomainMapper.transform(any(SessionEntity.class))).willReturn(session);
repository.getSessionList(1, resultCallback);
verify(dataStore).getSessionList(anyInt());
verify(dataToDomainMapper, times(3)).transform(any(SessionEntity.class));
verify(resultCallback).onResult(any(List.class));
}
Upvotes: 1
Views: 1116
Reputation: 7926
Check out tool for testing async methods called Awaitility. Very handy tool, saved me a lot of time on testing async methods.
Upvotes: 1
Reputation: 134
I believe you can move anonymous Runnable to inner (or nested) class and split testing on two parts: check that jobExecutor started execution with corresponding class instance and check that run() method of your inner/nested class works as you expect
Upvotes: 0