我有这个数据访问接口:
public interface UserDao {
void loadUsers(Handler<AsyncResult<List<User>>> handler);
}
它用于这样的服务:
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
}
});
}
}
现在,我的目的是对我的服务进行单元测试并模拟数据访问层。我想每次调用UserDao类的getUsers方法时返回一组固定的结果。
@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();
}
我该怎么做?它不符合正常的 Mockito 模式,当(serviceMock.method(any(Argument.class))).thenAnswer(new Result())因为mockResult不是从方法返回的,而是通过处理程序返回的。
存根函数。
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());
您可以使用 ArgumentCaptor 检查 loadUsers() 是否已使用非空处理程序调用。ArgumentCaptor 提供对处理程序的访问权限 您可以将准备好的结果传递给该结果(成功或失败的结果)
AsyncResult<List<User>> yourResult = ... //success or failure
ArgumentCaptor<Handler<AsyncResult<List<User>>>> captor = ArgumentCaptor.forClass(Handler.class);
Mockito.verify(userDao).loadUsers(captor.capture());
Handler<AsyncResult<List<User>>> handler = captor.getValue();
handler.handle(yourResult);
模拟Handler
也。
Handler mockedHandler = mock(Handler.class);
when(mockedHandler.result()).thenReturn(mockResult);
when(userDao.loadUsers(any(Handler.class))).thenReturn(mockedHandler);