I have this data access interface:
public interface UserDao {
void loadUsers(Handler<AsyncResult<List<User>>> handler);
}
And it's used in a service like this:
public class UserService {
private UserDao userDao;
public UserService(UserDao UserDao) {
this.userDao = userDao;
}
public void getUsers(Future<List<User>> future) {
userDao.loadUsers( ar ->{
if (ar.succeeded()){
List<User> users = ar.result();
// process users
future.complete(users);
}else {
// handle the error
}
});
}
}
Now my intention is to unit test my service and mock the data access layer. I want to return a fixed set of results every time getUsers method of UserDao class is called.
@Test
public void testGetUsers(TestContext context) {
Async async = context.async();
UserDao mockUserDao = Mockito.mock(UserDao.class);
UserService userService = new UserService(mockUserDao);
List<User> mockResult = Arrays.asList(new User(), new User());
/* (?) How to make mockUserDao return mockResult through its Handler argument? */
Future<List<User>> future = Future.future();
userService.getUsers(future);
future.setHandler(ar -> {
assertEquals(2, ar.result().size());
async.complete();
});
async.awaitSuccess();
}
How can I do that? It does not fit the normal Mockito pattern when(serviceMock.method(any(Argument.class))).thenAnswer(new Result()) as mockResult is not returned from the method per say but through the handler.
Stub the function.
public class TestUserDao implements UserDao {
void loadUsers(Handler<AsyncResult<List<User>>> handler) {
handler.apply(mockResult)
}
}
UserDao userDao = mock(UserDao.class, AdditionalAnswers.delegatesTo(new TestUserDao()));
verify(userDao).loadUsers(any());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With