我最初的 CRUD 方法生成一个准备好的语句并根据给定的参数设置字符串。
public class StatementUtility {
...
public static PreparedStatement getFoo(String bar, Connection conn) {
String query = "SELECT Foo FROM BarTable WHERE Bar = ?";
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(query);
pstmt.setString(1, bar);
}
catch (SQLException e) {
..
}
return pstmt;
}
...
}
在此声明中设置了我使用的数据库。然而,我在我的 MySQL 服务器中创建了一个 TestDB,我想在其中测试删除方法:
public static String deleteFoo(List<String> input) {
Connection conn = driver.connectCustomerDB(input);
try(PreparedStatement pstmt = StatementUtility.getFoo(String someString, conn)) {
...
}
}
这是我到目前为止的测试
@RunWith(PowerMockRunner.class)
@PrepareForTest(StatementUtility.class)
public class DBConnectionBTBAdminTest {
@Test
public void deleteTest() {
List<String> testInput = new ArrayList<>();
testInput.add("hello");
testInput.add("World");
Driver driver = new Driver();
Connection conn = driver.connectCustomerDB(testInput);
String query = "FooBarFooBarFooBarFooBarFooBarFooBarFooBarFooBar";
try {
//try mocking the Method within
BDDMockito.given(StatementUtility.getFoo(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), any(Connection.class))).willReturn(conn.prepareStatement(stringBuilder.toString()));
//call the method I want to test
SomeClass.deleteCategory(testInput, emptyArray);
...
} catch (SQLException e) {
...
}
}
}
我得到的错误是我最初创建 PreparedStatement 的方法中的 Nullpointer 异常,但这不是重点,因为我根本不想进入这个方法,而是 stub 。
我还尝试使用 Mockito 而不是 BDDMockito(参见此处:https://stackoverflow.com/a/21116014/8830232) 并使用真实值而不是 ArgumentMatchers。*
我还尝试了一些其他的东西,比如模拟连接
目前我正在使用 JUnit@4.12、Mockito@2.13.0、powermock@1.7.1
EDIT: For @glytching answer to work I had to downgrade mockito from 2.x to 1.x. >Dont forget to adjust powermock dependencies in that case
最佳答案
除了 @PrepareForTest(StatementUtility.class)
(告诉 PowerMock 准备此类进行测试)之外,您还必须为 StatementUtility
的所有方法启用静态模拟。您可以通过调用 ...
PowerMockito.mockStatic(StatementUtility.class);
...在您尝试对该模拟设置任何期望之前,在您的测试中。
例如:
@RunWith(PowerMockRunner.class)
@PrepareForTest(StatementUtility.class)
public class DBConnectionBTBAdminTest {
@Test
public void deleteTest() {
PowerMockito.mockStatic(StatementUtility.class);
List<String> testInput = new ArrayList<>();
testInput.add("hello");
testInput.add("World");
Driver driver = new Driver();
Connection conn = driver.connectCustomerDB(testInput);
String query = "FooBarFooBarFooBarFooBarFooBarFooBarFooBarFooBar";
try {
BDDMockito.given(StatementUtility.getFoo(...)).willReturn(...);
...
} catch (SQLException e) {
...
}
}
}
关于java - 在方法中模拟静态 PreparedStatement 方法时测试 CRUD 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48284352/