Skip to content

Added LogCaptor#869

Merged
akullpp merged 2 commits into
akullpp:masterfrom
Hakky54:master
Sep 21, 2020
Merged

Added LogCaptor#869
akullpp merged 2 commits into
akullpp:masterfrom
Hakky54:master

Conversation

@Hakky54

@Hakky54 Hakky54 commented Aug 20, 2020

Copy link
Copy Markdown
Contributor

LogCaptor is a library which will enable you to easily capture logging entries for unit testing purposes. It makes it possible to capture and assert SLF4J logs or other logging frameworks logs. It is very leightweight as it contains only one transitive dependency. Most of the developers dont bother testing log messages as it is time consuming and hard to configure. But if it is made really easy, probably more developers would also test their log messages. It should be painless and fun!

Below is an example use case:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FooService {

    private static final Logger LOGGER = LoggerFactory.getLogger(FooService.class);

    public void sayHello() {
        LOGGER.info("Keyboard not responding. Press any key to continue...");
        LOGGER.warn("Congratulations, you are pregnant!");
    }

}

And the following unit test:

import static org.assertj.core.api.Assertions.assertThat;

import nl.altindag.log.LogCaptor;
import org.junit.jupiter.api.Test;

public class FooServiceShould {

    @Test
    public void logInfoAndWarnMessages() {
        String expectedInfoMessage = "Keyboard not responding. Press any key to continue...";
        String expectedWarnMessage = "Congratulations, you are pregnant!";

        LogCaptor logCaptor = LogCaptor.forClass(FooService.class);

        FooService fooService = new FooService();
        fooService.sayHello();

        // Option 1 to assert logging entries
        assertThat(logCaptor.getInfoLogs()).containsExactly(expectedInfoMessage);
        assertThat(logCaptor.getWarnLogs()).containsExactly(expectedWarnMessage);

        // Option 2 to assert logging entries
        assertThat(logCaptor.getLogs())
                .hasSize(2)
                .containsExactly(expectedInfoMessage, expectedWarnMessage);
    }
}

@akullpp akullpp merged commit e002710 into akullpp:master Sep 21, 2020
@Hakky54 Hakky54 mentioned this pull request Sep 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants