本文介绍了使用 Mockito 模拟静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了一个工厂来生成 java.sql.Connection 对象:
I've written a factory to produce java.sql.Connection objects:
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.是否有模拟/验证此特定用例的好方法?
I'd like to validate the parameters passed to DriverManager.getConnection, but I don't know how to mock a static method. I'm using JUnit 4 and Mockito for my test cases. Is there a good way to mock/verify this specific use-case?
推荐答案使用 PowerMockito在 Mockito 之上.
Use PowerMockito on top of Mockito.
示例代码:
@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(...); }更多信息:
- 为什么 Mockito 不模拟静态方法?莉>
更多推荐
使用 Mockito 模拟静态方法
发布评论