简体   繁体   English

如何使用 junit 断言日志

[英]How to assert a log using junit

In my service I have conditions that should log an error if it's true.在我的服务中,如果它是真的,我有条件应该记录一个错误。 I would like test that in Junit test.我想在 Junit 测试中进行测试。 How can I do that?我怎样才能做到这一点?

package com.omb;

@Log4j2
@Component
@RequiredArgsConstructor
public class MyService {

    public void doSomething() {

        log.error("Log an error !");
    }
}

You could use this library and the getLog() method to assert a certain console output: https://stefanbirkner.github.io/system-rules/您可以使用这个库和 getLog() 方法来断言某个控制台 output: https://stefanbirkner.github/system-rule

The examples under "System.err and System.out" will give you some helpful examples. “System.err 和 System.out”下的示例将为您提供一些有用的示例。

I found this solution on Baeldung: https://www.baeldung.com/junit-asserting-logs我在 Baeldung 上找到了这个解决方案: https://www.baeldung.com/junit-asserting-logs

You can also use fe Mockito to create mock logger and set the logger using reflection to the service and at the end of the test you can verify if logger was called or not.您还可以使用 fe Mockito 创建模拟记录器并使用反射设置记录器到服务,并且在测试结束时您可以验证是否调用了记录器。 For setting private property like log for example you can use ReflectionTestUtils class form spring.例如,要设置像日志这样的私有属性,您可以使用 ReflectionTestUtils class 形式 spring。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM