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

1sbrub3j  于 2024-01-06  发布在  Spring
关注(0)|答案(1)|浏览(164)

在我们的spring Boot 应用程序中,我试图为批量插入操作方法编写mockito测试用例,但它不工作。
低于错误

java.lang.NullPointerException Suppressed.org.mockito.exceptions.misusing. InvalidPointerOfMatchersException:此处检测到错误放置或误用的参数匹配器。
我的代码如下

  1. @Repository
  2. public class AuditDao {
  3. @Value("${query}")
  4. private String queryForBatchInsert;
  5. @Value("${batchSize}")
  6. private int batchSize;
  7. @Autowired
  8. private JdbcTemplate jdbcTemplate;
  9. public int[][] batchInsert(List<Audit> auditList){
  10. int[][] updateCounts = jdbcTemplate.batchUpdate(
  11. queryForBatchInsert, auditList, batchSize, new ParameterizedPreparedStatementSetter<Audit>() {
  12. public void setValues(PreparedStatement ps, Audit audit) throws SQLException {
  13. ps.setLong(1, audit.getId);
  14. ps.setString(2, audit.getSourceType);
  15. ps.setString(3, audit.getJson);
  16. ps.setTimestamp(4, Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC"))));
  17. }
  18. });
  19. return updateCounts;
  20. }
  21. }

字符串

测试用例如下

  1. @Test
  2. public void testBatchInsert(){
  3. List<Audit> auditList = new ArrayList<Audit>();
  4. Audit audit = Mockito.mock(Audit.class);
  5. auditList.add(audit);
  6. when(jdbcTemplate.batchUpdate(ArgumentMatchers.<String>any(), any(), any(), any(ParameterizedPreparedStatementSetter.class))).thenReturn(new int[1][1]);
  7. assertEquals(new int[1][1], auditDao.batchInsert(auditList));
  8. }

9ceoxa92

9ceoxa921#

乍一看,你会发现,

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

字符串
期望int值作为batchSize,但是你把表示Object的matcher any()放在这一行:

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


尝试将其更改为:

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


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

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


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

展开查看全部

相关问题