如何在Spring Boot应用程序中为jdbcTemplate.batchUpdate编写mockito测试用例?

问题描述 投票:0回答:1

在我们的Spring Boot应用程序中,我尝试为批量插入操作方法编写mockito测试用例,但它不起作用。

出现以下错误

java.lang.NullPointerException Suppressed.org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 此处检测到放错位置或误用参数匹配器。

我的代码如下

@Repository
public class AuditDao {


  @Value("${query}")
  private String queryForBatchInsert;
  
  @Value("${batchSize}")
  private String 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
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));

}
spring-boot junit mockito junit4 junit5
1个回答
0
投票

乍一看似乎是与以下事实相关的异常:

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

期望 int 值作为batchSize,但是你在这一行中放置了代表对象的匹配器any():

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

尝试将其更改为:

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

但是,我看到您将batchSize用作字符串,并且没有使用任何隐式转换。

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

无论如何,您的问题与参数匹配器有关,具体来说,问题是由于 JdbcTemplate 中的 batchUpdate 方法的预期参数类型与 Mockito when().thenReturn 逻辑中使用的参数匹配器之间不匹配而出现的。

© www.soinside.com 2019 - 2024. All rights reserved.