当前位置 : 主页 > 网络安全 > 测试自动化 >

如何在TestNG中使用Mockito模拟jdbc连接和resultSet

来源:互联网 收集:自由互联 发布时间:2021-06-19
我必须编写一些单元测试但是我遇到了模拟ResultSet和jdbc Connection的问题. 我有这个方法: @Testpublic void test3() throws SQLException, IOException { Connection jdbcConnection = Mockito.mock(Connection.class); Res
我必须编写一些单元测试但是我遇到了模拟ResultSet和jdbc Connection的问题.

我有这个方法:

@Test
public void test3() throws SQLException, IOException {

    Connection jdbcConnection = Mockito.mock(Connection.class);
    ResultSet resultSet = Mockito.mock(ResultSet.class);

    Mockito.when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
    Mockito.when(resultSet.getString(1)).thenReturn("table_r3").thenReturn("table_r1").thenReturn("table_r2");
    Mockito.when(jdbcConnection
            .createStatement()
            .executeQuery("SELECT name FROM tables"))
            .thenReturn(resultSet);

    //when
    List<String> nameOfTablesList = null;
    try {
        nameOfTablesList = Helper.getTablesName(jdbcConnection);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //then
    Assert.assertEquals(nameOfTablesList.size(), 3);
}

并且错误显示在行executeQuery(“SELECT name FROM tables”)中,它听起来像这样:

java.lang.NullPointerException HelperTest.test3(HelperTest.java:71)

任何想法都出错了?

您需要在jdbcConnection.createStatement()上创建期望.

默认情况下,我相信返回null.

应该读类似的东西:

ResultSet resultSet = Mockito.mock(ResultSet.class);
Mockito.when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
Mockito.when(resultSet.getString(1)).thenReturn("table_r3").thenReturn("table_r1").thenReturn("table_r2");

Statement statement = Mockito.mock(Statement.class);
Mockito.when(statement.executeQuery("SELECT name FROM tables")).thenReturn(resultSet);

Connection jdbcConnection = Mockito.mock(Connection.class);
Mockito.when(jdbcConnection.createStatement()).thenReturn(statement);
网友评论