Mocking a SpringBoot RowMapper with Mockito

This is just a quick note for further reference.

Given a situation where you already tested your datasource or you can't test with a memory/test database, you probably want to mock the result of a Spring JdbcTemplate.query method execution. 

My method to get the data from database looks like this:
 
private List getModelList(){
    List myModelList = jdbcTemplate.query(QUERY, new Object[]{},(dataSet, i)-> return new MyModel(
        dataSet.getInteger(1),
        dataSet.getString(2)
    ));
}  
As you can see, I'm using a lambda expression to define a RowMapper and not a RowMapper class, this is a personal choice because I don't want to have one class for my model and another class for my mapper

So the test would look like this (not an actual test, is just for showing purposes):



 @Test
    public void testGetMyModel(){

        List expectedList = new ArrayList<>();

        expectedList.add(new MyModel(1,"John D"));

        expectedList.add(new MyModel(2,"Mike G"));
        
        expectedList.add(new MyModel(3,"Bryan S"));
        
        expectedList.add(new MyModel(4,"VJ D"));

        int expectedListSize = expectedList.size(); 
        when(jdbcTemplate.query(anyString(), any(Object[].class),any(RowMapper.class))).thenReturn(expectedList);
        List result = myServiceInstance.getMyModelList();
        Assert.assertEquals(expectedListSize,result.size());
    }
Not exactly a good test since I'm making use of `any` conditions, but in my case I was more interested on test a series of filters and validators with mock data.

Comentarios