使用PowerMock和Mockito模拟静态方法更新:
2022-09-01 19:07:59
我正在尝试验证对使用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