【问题标题】:Simulate jdbcTemplate query Exception with Spy (junit5)使用 Spy (junit5) 模拟 jdbcTemplate 查询异常
【发布时间】:2020-09-03 12:01:25
【问题描述】:

我使用的是 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());
}

运行“when”会抛出异常 java.lang.IllegalArgumentException: RowMapper is required 虽然它可以与 @MockBean(而不是我想要的 SpyBean)一起正常工作。

为什么它可以使用 mock 而不是 spy?我应该怎么做才能使其与@Spy 一起使用?

附:与

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

【问题讨论】:

  • 看到这个post,希望对你有帮助。
  • @Hantsy 谢谢!阅读后我明白我真的不会用模拟抛出异常,只是什么都不做。所以实际上我需要了解如何模拟 JdbcTemplate.query。

标签: java spring-boot jdbctemplate spy junit-jupiter


【解决方案1】:

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

要了解 Mockito 模拟和间谍,请查看来自 Baeldung 的 Mockito series,尤其是。 Injecting Mockito Mocks into Spring Beans.

我写了a simple testing code sample 使用 Mockito 和 Spring(不是 Spring Boot),监视真实实例,并通过存根模拟和替换方法

doNotingdoAnswerdoReturndoThrow的用法类似,在stubbing行为上调用这些方法,在执行spy对象的方法之前返回结果。

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

【讨论】:

    猜你喜欢
    • 2020-12-26
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多