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

标签 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类(class)。我想更改 connection它用作 lambda 参数。

我已经尝试过这个:

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.

如果我的问题得到解决,我将非常感激。 提前感谢您的帮助!

最佳答案

很少的东西。您是否使用 MockitoAnnotations.initMocks(this);@ExtendWith(MockitoExtension.class) 初始化模拟?您声明一个@Mock,但随后立即初始化该类的实例。

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

应该是:

@Mock
private DataAccessLayer dataAccessLayer; 

此外,DataAccessLayer 是一个最终类,除非您包含mockito-inline,否则您无法模拟该类。

关于java - 以通用功能接口(interface)作为参数的模拟方法 - Mockito,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61047397/

相关文章:

Python 单元测试 Google Bigquery

Python:制作全局单元测试功能

java - 我可以从泛型类型参数中获取 .class 吗?

java - 在 Jersey REST API 中为 CORS 配置 Web.xml

java - 如何防止 date.getMillisOf 空指针异常?

java - 简单程序中的 NullPointEException,无法找到修复方法

java - 基类上的 TestNg @BeforeTest 每个夹具仅发生一次

java - 关联 Java 字段类型和泛型参数

go - 如何编写一个允许指向多个基元类型的通用 Go 函数?

java - SQL异常 : Bad value for type long