Search code examples
junitmapperjdbi

JDBI mapper JUnit tests


I'd like to unit test my JDBI mapper classes since not all do trivial property mapping.

My testing class looks as follows:

  public class IdentRuleMapperTest {

  @Mock
  ResultSet resultSet;

  @Mock
  ResultSetMetaData resultSetMetaData;

  @Mock
  StatementContext ctx;

  IdentRuleMapper mapper;

  @Before
  public void setup() {
    mapper = new IdentRuleMapper();
  }

  @Test
  public void mapTest() throws SQLException {
    Mockito.when(resultSet.getString("ID")).thenReturn("The ID");
    Mockito.when(resultSet.getString("NAME")).thenReturn("The name");
    Mockito.when(resultSet.getString("REGULATION")).thenReturn("CRS");
    Mockito.when(resultSet.getString("JSON_ACTIONS_STRING")).thenReturn("the json string");
    IdentRule identRule = mapper.map(0, resultSet, ctx);

  }
}

The test throws NPE on the line

Mockito.when(resultSet.getString("ID")).thenReturn("The ID");

Anyone can point out to me why this won't work?


Solution

  • The annotation @Mock does not create the mock objects by itself. You have to add Mockito's JUnit rule as a field to your test

    @Rule
    public MockitoRule rule = MockitoJUnit.rule();
    

    or use its JUnit runner

    @RunWith(MockitoJUnitRunner.class)
    public class IdentRuleMapperTest {
      ...
    

    or create the mocks in an @Before method using MockitoAnnotations

    @Before
    public void initMocks() {
      MockitoAnnotations.initMocks(this);
    }