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

标签 java mysql unit-testing mockito junit4

我有一个使用 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/

相关文章:

java - 无法将文件上传到数据库

java - 将转换应用于整数和浮点除法的结果 : what's going on here?

mysql - 使用 MySQL 的查询中的查询

mysql - 将表中的一列显示为两个单独的列的子查询

javascript - 与 i18next 相关的间歇性单元测试失败

node.js - 用 Jest 模拟请求时出现 TypeError

unit-testing - 如何使用 MiniProfiler 查看单元测试中的配置文件信息

java - 相机图像处理

java - 绑定(bind)不匹配 : Generic class (of a Generic class extending Comparable (of a Generic class extending Comparable))

php - 这些字符串的正确检查语法是什么?