javamockitoinner-classes

Mockito instance of inner class


simpleJDBCCall.returningResultSet("test", new RowMapper<SomeObject> {
  
@Override
public SomeObject mapRow(Resultset r, int i) throws sqlexception {

//-----some code----
return someObject;

}

}

I want to execute the lines written inside the MapRow method using mockito


Solution

  • Mockito is used to stub methods, not really to execute methods. But it's still possible: you can stub your method with a dynamic Answer to call the method of the passed instance of the anonymous class.

    final SimpleJdbcCall simpleJDBCCall = Mockito.mock(…);
    when(simpleJDBCCall.returningResultSet(Mockito.anyString(), Mockito.any())).
        .thenAnswer(i -> {
          final RowMapper<SomeObject> rowMapper = i.getArgument(1);
          rowMapper.mapRow(…, …); // pass your desired ResultSet and integer
        });
    

    Calling now returningResultSet on your mock instance will immediately invoke the mapRow method on your second argument, passing any values that you specify.

    Note however what the official docs say about stubbing this way:

    Yet another controversial feature which was not included in Mockito originally. We recommend simply stubbing with thenReturn() or thenThrow(), which should be enough to test/test-drive any clean and simple code.