0

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.

rieckpil
  • 10,470
  • 3
  • 32
  • 56

2 Answers2

0

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);
rieckpil
  • 10,470
  • 3
  • 32
  • 56
  • Thank You for your inputs.I had already tried your recommendation but apparently on doing so i start getting compile time error as "Ambiguous method call. Both batchUpdate (String, Map[]) in NamedParameterJdbcTemplate and batchUpdate (String, SqlParameterSource[]) in NamedParameterJdbcTemplate match". Also for second recommendation similar compilation error appears. Any other recommendation? – Pavitar Feb 07 '21 at 21:10
  • Can you Update you question and and your SqlParameterSourceUtils class? – rieckpil Feb 08 '21 at 07:34
  • Found the solution , adding the cast to ArgumentMatchers worked. when(namedParameterJdbcTemplate.batchUpdate(anyString(), (SqlParameterSource[]) any())).thenReturn(rowsAffected); – Pavitar Feb 08 '21 at 16:55
0

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

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