gpt4 book ai didi

java - 使用 JDBC 模拟测试 execute() 方法

转载 作者:行者123 更新时间:2023-11-30 21:33:05 24 4
gpt4 key购买 nike

我有一个使用 statement.execute(query) 执行 SQL 语句的方法。如何测试这个 void 函数,因为它什么都不返回?我正在使用 Mockito 并使用@Spy。

附上了我的 execute() 方法的代码片段,它接收查询的 ArrayList:

public void execute(Statement statement, ArrayList<String> queryList) throws SQLException {
SQLException sqlException = null;
// read script line by line
for (String line : queryList) {
try {
statement.execute(line);
} catch (SQLException e1) {
if (null == sqlException)
sqlException = e1;
else {``
sqlException.addSuppressed(e1);
}
}
}
if (null != sqlException)
throw sqlException;
}

这是我的测试类,我需要用它来测试主类中的 void execute() 方法。我正在使用 Mocking 和 doNothing() 但我收到了不必要的 Stubbing 异常。

    @ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)
public class TestSQL {

@Spy
RunSQL runSQL=new RunSQL("dbConfig");
@Mock
BufferedReader br;
@Spy
ArrayList<String> queryList;
@Mock
Statement s;
@Mock
Connection c;
@Mock
RunSQL runsql;
@Test
public void testExecute() throws SQLException, IOException {
Mockito.when(br.readLine()).thenReturn("something");
runSQL.execute(s, queryList);
Mockito.doNothing().when(runsql).execute(s,queryList);
}
}

最佳答案

常规执行路径可以像下面这样测试:

@ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)
public class RunSQLTest {
@Test
public void queries_are_executed_one_by_one() throws SQLException {
//given:
RunSQL runSQL = new RunSQL("dbConfig");
List<String> queries = new ArrayList<>();
queries.add("query1");
queries.add("query2");
Statement statement = mock(Statement.class);

//when:
runSQL.execute(statement, queries);

//then:
verify(statement, times(1)).execute("query1");
verify(statement, times(1)).execute("query2");
verifyNoMoreInteractions(statement);
}
}

在这里,您只是严格断言所有查询都在一个接一个地成功执行,没有抛出任何异常。通过添加 verifyNoMoreInteractions(statement) 来实现严格性。如果您不添加它,那么 Mockito 只会尽力 stub 模拟交互。这是默认行为

关于java - 使用 JDBC 模拟测试 execute() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55253970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com