Search code examples
javaunit-testinggenericsmockitofunctional-interface

Mocking method with generic functional interface as an argument - Mockito


I am working on app and I decided to test it with JUnit5 and Mockito. I have a functional interface FunctionSQL<T, R>:

@FunctionalInterface
public interface FunctionSQL<T, R> {
    R apply(T arg) throws SQLException;
}

I have also DataAccessLayer class - constructor which obtains the databaseURL and connectionProperties is omitted due to readability issues:

public class DataAccessLayer {

    private String databaseURL;
    private Properties connectionProperties;

    public <R> R executeQuery(FunctionSQL<Connection, R> function){
        Connection conn = null;
        R result = null;
        try {
            synchronized (this) {
                conn = DriverManager.getConnection(databaseURL, connectionProperties);
            }

            result = function.apply(conn);

        } catch (SQLException ex) { }
        finally {
            closeConnection(conn);
        }

        return result;
    }

    private void closeConnection(Connection conn) {
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException ex) { }
    }

And abstract repository class:

public abstract class AbstractRepository {
    protected DataAccessLayer dataAccessLayer;

    public AbstractRepository() {
        dataAccessLayer = new DataAccessLayer();
    }
}

I have also created a implementation of repository:

public class ProgressRepository extends AbstractRepository {

    public List<ProgressEntity> getAll() {
        String sql = "SELECT * FROM progresses";
        return dataAccessLayer.executeQuery(connection -> {
            PreparedStatement statement = connection.prepareStatement(sql);

            ResultSet result = statement.executeQuery();


            List<ProgressEntity> progresses = new ArrayList<>();

            while (result.next()){
                ProgressEntity progressEntity = new ProgressEntity();
                progresses.add(progressEntity);
            }

            statement.close();
            return progresses;
        });
    }

I have tried to find a solution to mock the executeQuery(...) method from DataAccessLayer class. I would like like to change the connection which is used as lambda argument.

I have tried this one:

class ProgressRepositoryTest {

    @Mock
    private static DataAccessLayer dataAccessLayer = new DataAccessLayer();

    private static Connection conn;

    @BeforeEach
    void connecting() throws SQLException {
        conn = DriverManager.getConnection("jdbc:h2:mem:test;", "admin", "admin");
    }

    @AfterEach
    void disconnecting() throws SQLException {
        conn.close();
    }

    @Test
    void getAllTest(){

        when(dataAccessLayer.executeQuery(ArgumentMatchers.<FunctionSQL<Connection, ProgressEntity>>any())).then(invocationOnMock -> {
            FunctionSQL<Connection, ProgressEntity> arg = invocationOnMock.getArgument(0);
            return arg.apply(conn);
        });

        ProgressRepository progressRepository = new ProgressRepository();

        progressRepository.getAll();

    }
}

But I'm getting an error:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is returning an object 
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
    when(mock.get(any())); // bad use, will raise NPE
    when(mock.get(anyInt())); // correct usage use

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

I would be very grateful for the solution of my problem. Thanks for help in advance!


Solution

  • Few things. Did you initialize your mocks with either MockitoAnnotations.initMocks(this); or @ExtendWith(MockitoExtension.class)? You declare a @Mock but then you initialize an instance of the class right away.

    @Mock
    private static DataAccessLayer dataAccessLayer = new DataAccessLayer();
    

    Should just be:

    @Mock
    private DataAccessLayer dataAccessLayer; 
    

    Also DataAccessLayer is a final class which you cannot mock unless you include mockito-inline.