Vertx Mock与Handler <asyncresult <>&gt;的异步方法争论

时间:2018-03-15 05:07:28

标签: testing mocking mockito vert.x

我有这个数据访问界面:

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()) as mockResult 不会从每个方法,但通过处理程序。

3 个答案:

答案 0 :(得分:1)

如果使用非空处理程序使用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);

答案 1 :(得分:0)

模拟Handler

Handler mockedHandler = mock(Handler.class);
when(mockedHandler.result()).thenReturn(mockResult);
when(userDao.loadUsers(any(Handler.class))).thenReturn(mockedHandler);

答案 2 :(得分:0)

存根功能。

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