使用Spyjunit5模拟jdbcTemplate查询异常

问题描述

我使用Spy而不是Mock,因为我想要其他方法的常规功能。 我想在调用jdbcTemplate查询时模拟一个异常。

JdbcTemplate.query原型是public <T> List<T> query(String sql,RowMapper<T> rowMapper) throws DataAccessException,我这样称呼它:

jdbcTemplate.query("select 1 from dual",new SingleColumnRowMapper<>());

这是我的间谍等级:

@SpyBean
JdbcTemplate jdbcTemplate;

这是测试:

@Test
void testDbIsDown() {
    when(jdbcTemplate.query(anyString(),any(SingleColumnRowMapper.class)))
            .thenThrow(new DataAccessResourceFailureException("s"));
    Health health = dbServiceValidator.health();
    assertThat(health.getStatus().getCode())
            .isEqualTo(Health.down().build().getStatus().getCode());
}

运行“何时”引发异常java.lang.IllegalArgumentException: RowMapper is required可以与@MockBean(而不是我想要的SpyBean)配合使用。

为什么它可以与模拟一起使用但不能与间谍一起使用?我应该怎么做才能使其与@Spy一起使用?

P.S。与

相同
when(jdbcTemplate.query(anyString(),any(RowMapper.class)))
        .thenThrow(DataAccessException.class);

解决方法

当您使用Spring Boot @MockBean或@SpyBean时,两者都知道Spring。

要了解Mockito的模拟和间谍行为,请检查特别是Baeldung的Mockito seriesInjecting Mockito Mocks into Spring Beans

我已经写过a simple testing code sample,涉及使用Mockito和Spring(不是Spring Boot),在实际实例上使用 spy以及通过存根来模拟和替换方法

doNotingdoAnswerdoReturndoThrow的用法类似,在执行间谍对象的方法之前,对存根行为调用这些方法以返回结果

如果您有兴趣,请从我的github检查有关Mockito的测试代码示例,例如。 this test

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...