Java 8 lamba mocking feature with Mockito 2

I am using JDBI 3 and wrote the following utility function.

public class JdbiHelper {
    // ...

    public <T, DAO> T fetch(final Function<DAO, T> function, Class<DAO> daoClass) {
        return dbi.withHandle(handle -> {
           final DAO dao = handle.attach(daoClass);
           try {
               return function.apply(dao);
           }
           finally {
               handle.close();
           }
        });
    }
}

which I can call in methods like this

public Optional<Account> findByEmailAddress(final String emailAddress) {
    if (!exists(emailAddress))
        return Optional.empty();
    return jdbiHelper.fetch(dao -> ofNullable(dao.selectByEmailAddress(emailAddress)), AccountDAO.class);
}

private boolean exists(final String emailAddress) {
    return jdbiHelper.fetch(dao -> dao.count(emailAddress) > 0, AccountDAO.class);
}

I am trying to write a test for findByEmailAddressmocking jdbiHelperusing Mockito 2, but cannot decide how to mock the dao -> part of the method.

I tried using jdbiHelper.fetch(any(Function.class), eq(AccountDAO.class)), but since there are two different expectations for what to return, he is not trying to use one or the other.

Passing to the mocked function calls NPE, because the dao parameter is null.

+4
source share

Source: https://habr.com/ru/post/1682379/


All Articles