本文翻译自:Mocking static methods with Mockito
I've written a factory to produce java.sql.Connection
objects: 我已经写了一个工厂来产生java.sql.Connection
对象:
public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {
@Override public Connection getConnection() {
try {
return DriverManager.getConnection(...);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
I'd like to validate the parameters passed to DriverManager.getConnection
, but I don't know how to mock a static method. 我想验证传递给DriverManager.getConnection
的参数,但是我不知道如何模拟静态方法。 I'm using JUnit 4 and Mockito for my test cases. 我在测试用例中使用的是JUnit 4和Mockito。 Is there a good way to mock/verify this specific use-case? 有没有模拟/验证此特定用例的好方法?
#1楼
参考:https://stackoom.com/question/1QYTj/用Mockito模拟静态方法
#2楼
To mock static method you should use a Powermock look at: https://github.com/powermock/powermock/wiki/MockStatic . 要模拟静态方