【问题标题】:How to ignore a method call inside a method that is being tested?如何忽略正在测试的方法中的方法调用?
【发布时间】:2021-03-23 10:13:16
【问题描述】:

我正在尝试使用 mockmvc 进行测试,但失败并显示以下错误消息:

引起: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);
}

【问题讨论】:

    标签: java spring-boot testing apache-kafka mockmvc


    【解决方案1】:

    你能模拟 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));
    

    【讨论】:

    • 谢谢你,成功了!
    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多