如何验证JUnit中logger.error(字符串消息,的Throwable t)的使用测试用例的Mockito

时间:2019-01-31 08:52:13

标签: java spring-boot junit mockito

我正在尝试测试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
    );

所需参数和实际参数都相同,但仍会引发错误。谁能帮我这个忙吗?

1 个答案:

答案 0 :(得分: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);

应该工作