使用PowerMock和Mockito模拟静态方法

25
我正在尝试使用JUnit、Mockito和PowerMock验证对java.sql.DriverManager.getConnection的调用。
这是我的测试案例:
@RunWith(PowerMockRunner.class)
@PrepareForTest(DriverManager.class)
public class MySQLDatabaseConnectionFactoryTest {

    private ConfigurationService configurationService;
    private MySQLDatabaseConnectionFactory reference;

    @Before
    public void setUp() throws Exception {
        this.reference = new MySQLDatabaseConnectionFactory();
    }

    @Test
    public void testGetConnection() throws SQLException {
//      setup
        Connection connection = mock(Connection.class);

        PowerMockito.mockStatic(DriverManager.class);

        when(DriverManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection);

//      run
        this.reference.getConnection();

//      verify
        PowerMockito.verifyStatic();
        DriverManager.getConnection("jdbc:mysql://myhost:1111/database", "username", "password");
    }

}

以下是被测试的代码:

public class MySQLDatabaseConnectionFactory implements
        DatabaseConnectionFactory {

    @Override
    public Connection getConnection(IApplicationInstance appInstance) {         
        try {
            return DriverManager.getConnection(String.format("jdbc:mysql://%s:%d/%s", 
                    MYSQL_HOST, MYSQL_PORT, MYSQL_DATABASE), MYSQL_USERNAME, MYSQL_PASSWORD);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

有趣的是,这段代码在出现 java.sql.SQLException 时会失败:

java.lang.RuntimeException: java.sql.SQLException: No suitable driver found for jdbc:mysql://myhost:1111/database

现在,我可以轻松地确保我的SQL驱动程序(在这种情况下是MySQL)在测试时加载,但为什么静态方法没有完全模拟出来而没有副作用呢?

更新:

我已经更好地隔离了问题。我在我的测试用例中添加了一个测试方法,尝试从DriverManager获取连接:

@Test
public void testSomething() {
    Connection conn = mock(Connection.class);
    mockStatic(DriverManager.class);
    when(DriverManager.getConnection(anyString())).thenReturn(conn);
    Connection c = DriverManager.getConnection("whut");
    verifyStatic();
    DriverManager.getConnection("whut");
}

这个测试实际上通过了,而另一个测试仍然失败。似乎 PowerMock 没有模拟 MySQLDatabaseConnectionFactory 内部类的引用。我该如何解决?


你在测试中调用了 this.reference.getConnection();,但是这个 public Connection getConnection(IApplicationInstance appInstance) 是什么意思呢?你能澄清一下吗? - MariuszS
1个回答

32

@PrepareForTest注释的值更改为MySQLDatabaseConnectionFactory.class将解决此问题。

这个注释告诉PowerMock为测试准备某些类。需要使用该注释定义的类通常是需要进行字节码操作的类。这包括最终类、带有final、private或static修饰符的类。

在这种情况下,PowerMockito必须用模拟代码替换对静态方法DriverManager.getConnection的调用。这是通过使用字节码操作完成的。

完整代码

@RunWith(PowerMockRunner.class)
@PrepareForTest(MySQLDatabaseConnectionFactory.class)
public class MySQLDatabaseConnectionFactoryTest {

    private MySQLDatabaseConnectionFactory reference;

    @Before
    public void setUp() throws Exception {
        reference = new MySQLDatabaseConnectionFactory();
    }

    @Test
    public void testGetConnection() throws SQLException {

        // given
        PowerMockito.mockStatic(DriverManager.class);
        BDDMockito.given(DriverManager.getConnection(anyString(), anyString(), anyString()))
             .willReturn(mock(Connection.class));

        // when
        reference.getConnection();

        // then
        PowerMockito.verifyStatic();
        DriverManager.getConnection("jdbc:mysql://myhost:1111/database", "username", "password");
    }
}

感谢@Szpak帮助我解决了这个问题!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接