Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

question from:https://stackoverflow.com/questions/66065250/spring-boot-with-mockito-mocking-namedparameterjdbctemplate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
345 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...