java - How to mock jdbc connection and resultSet using Mockito in TestNG -
i have write unit tests have problem mocking resultset
, jdbc connection
.
i have method:
@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 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); }
and error showing in line executequery("select name tables")
, sounds this:
java.lang.nullpointerexception helpertest.test3(helpertest.java:71)
any ideas whats going wrong?
you need create expectation on jdbcconnection.createstatement()
.
by default, believe null
returned.
should read like:
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 tables")).thenreturn(resultset); connection jdbcconnection = mockito.mock(connection.class); mockito.when(jdbcconnection.createstatement()).thenreturn(statement);
Comments
Post a Comment