我已经写了一家工厂来生产java.sql.Connection物体:
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 4和Mockito。有没有模拟或验证此特定用例的好方法?
DriverManager.getConnection
JUnit 4
Mockito
在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(...); }