1

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 !");
    }
}
Andrej Istomin
  • 2,527
  • 2
  • 15
  • 22
Ousmane MBINTE
  • 664
  • 4
  • 15
  • 37
  • with log4j2 you can also mock an `Appender` similar to https://stackoverflow.com/questions/42096800/log4j2-mock-appender or https://codingcraftsman.wordpress.com/2015/04/28/log4j2-mocking-with-mockito-and-junit/ – zapl Sep 19 '22 at 16:47
  • Just add appender. https://stackoverflow.com/a/3717461/13523946 – notAPPP Sep 19 '22 at 16:48

1 Answers1

0

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.

Marko
  • 101
  • 6