我必须编写一些单元测试但是我遇到了模拟ResultSet和jdbc Connection的问题. 我有这个方法: @Testpublic void test3() throws SQLException, IOException { Connection jdbcConnection = Mockito.mock(Connection.class); Res
我有这个方法:
@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);