我写了一个工厂来生产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
在 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(...); }
更多信息: