Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I assert my log message when the log is created by lombok

Tags:

java

junit

lombok

I have the following code:

@Component
@Slf4j
public class MyClass {

    private OtherClass otherClass;

    @Autowired
    public MyClass(OtherClass otherClass) {
        this.otherClass = otherClass;
    }

    public void start() {
        try {
            otherClass.execute();
        } catch (FeatureException exception) {
            log.warn(exception.getMessage());
        }
    }

I want do test to verify the log message. I dont know how.

Thanks

like image 400
Rafael Chaves Avatar asked Nov 28 '16 18:11

Rafael Chaves


People also ask

Is Lombok is used for logging?

Use Log Annotations. Lombok provides several log annotations to work with different logging libraries.

How do you log test unit?

ALL: in unit tests you can change the log level of the logger, to verify that when a certain log level is set, certain messages will no longer be logged. For example, if the log level were to be set to WARN, then the FruitLogger should no longer log the message body.

What is Slf4j annotation?

Annotation Type Slf4jCauses lombok to generate a logger field. Complete documentation is found at the project lombok features page for lombok log annotations.

What is LogCaptor?

LogCaptor is a library which will enable you to easily capture logging entries for unit testing purposes.


1 Answers

The SLF4J project recommends using the library SLF4J Test for this use case.

In your case (using Hamcrest and Mockito as well):

public class MyClassTest {

  TestLogger logger = TestLoggerFactory.getTestLogger(MyClass.class);

  @Test
  public void testStart_loggingFailureMessage() {
    OtherClass otherClass = mock(OtherClass.class);
    MyClass myClass = new MyClass(otherClass);

    when(otherClass.execute()).thenThrow(new FeatureException("Some text"));

    myClass.start();

    assertThat(logger.getLoggingEvents(), is(asList(LoggingEvent.warn("Some text"))));
  }

  @After
  public void clearLoggers() {
    TestLoggerFactory.clear();
  }
}
like image 68
Olivier Grégoire Avatar answered Dec 29 '22 00:12

Olivier Grégoire