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



我已经编写了一个集成,用于测试删除函数,如下所示

@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 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创建mock并使用thenCallRealMethod()调用真实方法的另一种方法

@MockBean
private UserRepository userRepository

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

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

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

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

最新更新