微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何验证在spring集成测试中调用了void函数

如何解决如何验证在spring集成测试中调用了void函数

我编写了一个集成来测试删除功能,如下所示

@Test
void deleteUserstest() {
    Map<String,String> params = new HashMap<>();
    params.put("id","21");
    this.template.delete("/v1/users/{id}",params);
    :
}

我面临的问题是,由于它是一个函数,我想验证下面的函数是在内部调用

userRepository.deleteById(21)

在单元测试中我通常使用这样的东西

verify(userRepository,times(1)).deleteById((long) 21);

但上面的一个是基于 mockito 的函数,我不能在集成测试中使用

谁能帮我在 Spring Integration 测试中验证这个功能

我使用的是 Spring 5,Spring Boot 2.1

解决方法

集成测试在真实数据库上进行。只需确保实体在调用 delete 之前存储在您的数据库中,而不是在调用 delete 之后存储在您的数据库中。

@BeforeEach
public void setDatabase() {
    client1 = new Client();
    client1.setName("Karl");
    client2 = new Client();
    client2.setName("Pauline");

    testEntityManager.persist(client1);
    testEntityManager.persist(client2);
    testEntityManager.flush();
}
@Test
public void deleteTest() {
    clientRepository.deleteById(client1.getId());

    List<Client> clientListActual = clientRepository.findAll();
    boolean clientExists = clientListActual.contains(client1);

    assertFalse(clientExists);
    assertEquals(1,clientListActual.size());
}
,

我建议使用 @SpyBean,这里是使用 spybean

的示例

Spy 包装了真正的 bean,但允许您验证方法调用和模拟单个方法,而不会影响真正 bean 的任何其他方法。因此,通过使 userRepository 成为 SpyBean,我们可以只模拟我们要在测试用例中模拟的方法,而让其他方法保持不变。

另一种方法,您还可以使用 @MockBean 创建模拟并使用 thenCallRealMethod() 调用真实方法

@MockBean
private UserRepository userRepository

然后说调用一个真正的方法

// Call a real method of a Mocked object
when(userRepository.deleteById(21l)).thenCallRealMethod();

所以使用上面的语句其实是调用了真正的方法,现在可以验证了

verify(userRepository,times(1)).deleteById(21l);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。