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.
It seems that you're not using the correct import for
any()
because if it would be the correctArgumentMatchers.any()
from Mockito, Mockito would complain that you don't use anArgumentMatcher
for both parameters of.batchUpdate()
.You can statically import it with
import static org.mockito.ArgumentMatchers.*;
or useArgumentMatchers.any()
.So as first step, try the following:
or be less generic and match the return type of
SqlParameterSourceUtils.createBatch()
with: