jeudi 26 mars 2015

How to test async method from not mocking object with Mockito?

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));
}

Aucun commentaire:

Enregistrer un commentaire