How to write mockito test case for jdbcTemplate.batchUpdate in spring boot application?

65 Views Asked by At

In our spring boot application, I am trying to write mockito test case for batch insert operation method but its not working.

Getting below error

java.lang.NullPointerException Suppressed.org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Misplaced or misused argument matcher detected here.

My code is as below

@Repository
public class AuditDao {


  @Value("${query}")
  private String queryForBatchInsert;
  
  @Value("${batchSize}")
  private int batchSize;
  
  @Autowired
  private JdbcTemplate jdbcTemplate;


   public int[][] batchInsert(List<Audit> auditList){
      int[][] updateCounts = jdbcTemplate.batchUpdate(
      queryForBatchInsert, auditList, batchSize, new ParameterizedPreparedStatementSetter<Audit>() {
      public void setValues(PreparedStatement ps, Audit audit) throws SQLException {
      ps.setLong(1, audit.getId);
      ps.setString(2, audit.getSourceType);
      ps.setString(3, audit.getJson);
      ps.setTimestamp(4, Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC"))));
      }
      });
      return updateCounts;
   }

}

Test case is as below

@Test
public void testBatchInsert(){

List<Audit> auditList = new ArrayList<Audit>();
Audit audit = Mockito.mock(Audit.class);
auditList.add(audit);

when(jdbcTemplate.batchUpdate(ArgumentMatchers.<String>any(), any(), any(), any(ParameterizedPreparedStatementSetter.class))).thenReturn(new int[1][1]);
assertEquals(new int[1][1], auditDao.batchInsert(auditList));

}
1

There are 1 best solutions below

0
Ruslan Zinovyev On

At first glance seems like exception you see related to the fact that

batchUpdate(String sql, Collection<T> batchArgs, int batchSize, ParameterizedPreparedStatementSetter<T> pss)

expects int value as a batchSize, however you put matcher any() which represents Object in this line:

when(jdbcTemplate.batchUpdate(ArgumentMatchers.<String>any(), any(), any(), any(ParameterizedPreparedStatementSetter.class))).thenReturn(new int[1][1]);

Try to change it to:

when(jdbcTemplate.batchUpdate(ArgumentMatchers.<String>any(), any(), anyInt(), any(ParameterizedPreparedStatementSetter.class))).thenReturn(new int[1][1]);

However, I see that you are using batchSize as a String, and you don't use any implicit conversion.

 @Value("${batchSize}")
 private String batchSize;

Anyway, your issue relates to the argument matcher, specifically, the problem appears from the mismatch between expected argument types of the batchUpdate method in JdbcTemplate and the argument matchers used in your Mockito when().thenReturn logic.