以通用功能接口作为参数的模拟方法-Mockito

时间:2020-04-05 18:23:43

标签: java unit-testing generics mockito functional-interface

我正在开发应用程序,因此决定使用JUnit5和Mockito对其进行测试。我有一个功能界面FunctionSQL<T, R>

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

我还有DataAccessLayer类-由于易读性问题,省略了获取databaseURLconnectionProperties的构造函数:

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) { }
    }

和抽象存储库类:

public abstract class AbstractRepository {
    protected DataAccessLayer dataAccessLayer;

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

我还创建了存储库的实现:

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

我试图找到一种解决方案来模拟executeQuery(...)类中的DataAccessLayer方法。我想更改用作lambda参数的connection

我尝试过这个:

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

    }
}

但是我遇到一个错误:

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.

我非常感谢您解决我的问题。 预先感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

几件事。您是否使用MockitoAnnotations.initMocks(this);@ExtendWith(MockitoExtension.class)初始化了模拟?您声明了@Mock,然后立即初始化了该类的实例。

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

应该是:

@Mock
private DataAccessLayer dataAccessLayer; 

DataAccessLayer也是最后一个类,除非您包含模仿行内联,否则您无法模拟。