Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertx Mock an async method with Handler<AsyncResult<>> argument

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.

like image 854
Vahid Yaghini Avatar asked Oct 28 '22 16:10

Vahid Yaghini


1 Answers

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());
like image 151
Anders B Avatar answered Nov 10 '22 16:11

Anders B