How to assert a log using junit

Viewed 39

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 !");
    }
}
3 Answers

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.

Related