簡體   English   中英

Mocking 方法以通用功能接口作為參數 - Mockito

[英]Mocking method with generic functional interface as an argument - Mockito

我正在開發應用程序,我決定使用 JUnit5 和 Mockito 對其進行測試。 我有一個功能接口FunctionSQL<T, R>

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

我還有 DataAccessLayer class - 由於可讀性問題,省略了獲取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) { }
    }

和抽象存儲庫 class:

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

我試圖找到一個解決方案來模擬DataAccessLayer class 中的executeQuery(...)方法。 我想更改用作 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.

我將非常感謝我的問題的解決方案。 提前感謝您的幫助!

一些事情。 您是否使用MockitoAnnotations.initMocks(this);初始化了您的模擬? @ExtendWith(MockitoExtension.class) 您聲明了一個@Mock ,但隨后立即初始化了 class 的一個實例。

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

應該只是:

@Mock
private DataAccessLayer dataAccessLayer; 

DataAccessLayer 也是最終的 class ,除非您包含 mockito-inline,否則您無法模擬它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM