Spring boot with Mockito mocking NamedParameterJdbcTemplate

813 Views Asked by At

Trying to unit test a method which is defined as :

public void myMethod(List<? extends MyModel> model){
  int[] result = namedParameterJdbcTemplate.batchUpdate("update query", SqlParameterSourceUtils.createBatch(model));
}

In my test class i am defining test method as

class MyTestClass{

  @Mock
  NamedParameterJdbcTemplate namedParameterJdbcTemplate;
   
  @InjectMocks
  MyDao dao;

  @Test
  public void testMyMethod() {

    final int[] rowsAffected = new int[]{1,2};

    when(namedParameterJdbcTemplate.batchUpdate(any(), SqlParameterSourceUtils.createBatch(Arrays.asList(anySet())))).thenReturn(rowsAffected);
        
    List<MyModel> myModels = new ArrayList<>();
    MyModel mymodel = new MyModel();
    mymodel.setSomeParam("");
    myModels.add(mymodel);
    dao.myMethod(myModels);
        
  }
}

While running this test method , i am getting NullPointerException in called method(myMethod()). int[] result is coming as null. My understanding is it should get the result from the stub in the mock. Please help me understand what am i doing wrong.

2

There are 2 best solutions below

3
On

It seems that you're not using the correct import for any() because if it would be the correct ArgumentMatchers.any() from Mockito, Mockito would complain that you don't use an ArgumentMatcher for both parameters of .batchUpdate().

You can statically import it with import static org.mockito.ArgumentMatchers.*; or use ArgumentMatchers.any().

So as first step, try the following:

when(namedParameterJdbcTemplate.batchUpdate(ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(rowsAffected);

or be less generic and match the return type of SqlParameterSourceUtils.createBatch() with:

// I don't know what SqlParameterSourceUtils.createBatch() returns, so you might have to adjust it
when(namedParameterJdbcTemplate.batchUpdate(ArgumentMatchers.any(), ArgumentMatchers.eq("SOME RETURN"))).thenReturn(rowsAffected);
0
On

It worked by adding the cast to the Argument matchers: Updated Code :

    when(namedParameterJdbcTemplate.batchUpdate(anyString(), (SqlParameterSource[]) any())).thenReturn(rowsAffected);