一尘不染

Java-用Mockito模拟静态方法

java

我已经写了一家工厂来生产java.sql.Connection物体:

public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {

    @Override public Connection getConnection() {
        try {
            return DriverManager.getConnection(...);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

我想验证传递给的参数DriverManager.getConnection,但不知道如何模拟静态方法。我在测试用例中使用的是JUnit 4Mockito。有没有模拟或验证此特定用例的好方法?


阅读 1149

收藏
2020-02-25

共1个答案

一尘不染

在Mockito上使用PowerMockito。

示例代码:

@RunWith(PowerMockRunner.class)
@PrepareForTest(DriverManager.class)
public class Mocker {

    @Test
    public void shouldVerifyParameters() throws Exception {

        //given
        PowerMockito.mockStatic(DriverManager.class);
        BDDMockito.given(DriverManager.getConnection(...)).willReturn(...);

        //when
        sut.execute(); // System Under Test (sut)

        //then
        PowerMockito.verifyStatic();
        DriverManager.getConnection(...);

    }
2020-02-25