我正在尝试使用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