如何忽略正在测试的方法中的方法调用?
How to ignore a method call inside a method that is being tested?
我正在尝试使用 mockmvc 进行测试,但失败并显示以下错误消息:
Caused by: org.apache.kafka.common.config.ConfigException
我们的服务层中有 Kafka 作为依赖项,它在我们正在测试的方法中被调用。
有没有办法在测试期间忽略该特定调用?
在下面的示例中,我们希望在测试期间忽略 notifyHrcOfInfectedUser()
。
public UserDto changeInfectionStatus(String deviceId) {
User user = this.userRepository.findById(deviceId)
.orElseThrow(() -> new EntityNotFoundException("Could not find user with id " + deviceId));
if (!hasPassedTwoWeeksMinimumRecoveryTime(user))
throw new InfectionStatusException("Unable to change infection status since it has not been at least" +
" two weeks since the last change.");
UserDto updatedUser = updateStatus(user).convertToDto();
notifyHrcOfInfectedUser(updatedUser.isInfected(), deviceId); // <-- Ignore this call during tests
return updatedUser;
}
private void notifyHrcOfInfectedUser(boolean isInfected, String deviceId) {
if (isInfected)
kafkaSender.publish("infection-contact", deviceId);
}
你能模拟 kafkaSender 对象吗?然后我们可以做类似...
final KafkaSender mockKafkaSender = Mockito.mock(KafkaSender.class);
Mockito.doNothing().when(mockKafkaSender).publish(any(),any());
更新...
或者更准确地说
Mockito.doNothing().when(mockKafkaSender).publish(eq("infection-contact"),eq(expectedDeviceId));
我正在尝试使用 mockmvc 进行测试,但失败并显示以下错误消息:
Caused by: org.apache.kafka.common.config.ConfigException
我们的服务层中有 Kafka 作为依赖项,它在我们正在测试的方法中被调用。
有没有办法在测试期间忽略该特定调用?
在下面的示例中,我们希望在测试期间忽略 notifyHrcOfInfectedUser()
。
public UserDto changeInfectionStatus(String deviceId) {
User user = this.userRepository.findById(deviceId)
.orElseThrow(() -> new EntityNotFoundException("Could not find user with id " + deviceId));
if (!hasPassedTwoWeeksMinimumRecoveryTime(user))
throw new InfectionStatusException("Unable to change infection status since it has not been at least" +
" two weeks since the last change.");
UserDto updatedUser = updateStatus(user).convertToDto();
notifyHrcOfInfectedUser(updatedUser.isInfected(), deviceId); // <-- Ignore this call during tests
return updatedUser;
}
private void notifyHrcOfInfectedUser(boolean isInfected, String deviceId) {
if (isInfected)
kafkaSender.publish("infection-contact", deviceId);
}
你能模拟 kafkaSender 对象吗?然后我们可以做类似...
final KafkaSender mockKafkaSender = Mockito.mock(KafkaSender.class);
Mockito.doNothing().when(mockKafkaSender).publish(any(),any());
更新...
或者更准确地说
Mockito.doNothing().when(mockKafkaSender).publish(eq("infection-contact"),eq(expectedDeviceId));