【问题标题】:How to verify logger.error(String message, Throwable t) in Junit testcase using Mockito如何使用 Mockito 在 Junit 测试用例中验证 logger.error(String message, Throwable t)
【发布时间】:2019-01-31 08:52:12
【问题描述】:

我正在尝试测试 Kafka 回调 onFailure 方法:

     @Override
        public void onFailure(Throwable ex) {
        logger.error("Failure while sending message in kafka.", ex);
            }

My test case code using Mockito. I am setting exception in object of class SettableListenableFuture.



   SettableListenableFuture<SendResult<String, DeserializationResult<EnvelopeExpanded<SpecificRecord>>>> future2 = new SettableListenableFuture<>();
                future2.setException(new Exception("Could not publish to Kafka"));
    Exception ex = new Exception("Could not publish to Kafka");
    verify(logger, times(1)).error("Failure while sending message in kafka.", ex);

我收到了这个错误

  Argument(s) are different! Wanted:
    logger.error(
        "Failure while sending message in kafka.",
        java.lang.Exception: Could not publish to Kafka
    );

    Actual invocation has different arguments:
    logger.error(
        "Failure while sending message in kafka.",
        java.lang.Exception: Could not publish to Kafka
    );

想要的和实际的参数都是一样的,但它仍然会抛出错误。谁能帮我解决这个问题??

【问题讨论】:

    标签: java spring-boot junit mockito


    【解决方案1】:

    System.out.println(new Exception("Could not publish to Kafka").equals(new Exception("Could not publish to Kafka"))) 将打印false

    所以

       Exception ex = new Exception("Could not publish to Kafka");
       SettableListenableFuture<...> future2 = new SettableListenableFuture<>();
                future2.setException(ex);
       verify(logger, times(1)).error("Failure while sending message in kafka.", ex);
    

    应该工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多