In my service I have conditions that should log an error if it's true. I would like test that in Junit test. How can I do that ?
package com.omb;
@Log4j2
@Component
@RequiredArgsConstructor
public class MyService {
public void doSomething() {
log.error("Log an error !");
}
}
CodePudding user response:
You could use this library and the getLog() method to assert a certain console output: https://stefanbirkner.github.io/system-rules/
The examples under "System.err and System.out" will give you some helpful examples.
CodePudding user response:
I found this solution on Baeldung : https://www.baeldung.com/junit-asserting-logs
CodePudding user response:
You can also use f.e. 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. For setting private property like log for example you can use ReflectionTestUtils class form spring.