DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Finally, an ORM That Matches Modern Architectural Patterns!
  • The Hidden Costs of Lombok in Enterprise Java Solutions
  • Mastering Unit Testing and Test-Driven Development in Java
  • Comprehensive Guide to Unit Testing Spring AOP Aspects

Trending

  • Unmasking Entity-Based Data Masking: Best Practices 2025
  • AI-Based Threat Detection in Cloud Security
  • Memory Leak Due to Time-Taking finalize() Method
  • Docker Base Images Demystified: A Practical Guide
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Unit Testing Log Messages Made Easy

Unit Testing Log Messages Made Easy

Unit testing presents specific challenges around logging. A developer and DZone Core members discusses an open source project he created to help.

By 
Hakan Altındağ user avatar
Hakan Altındağ
·
Updated Dec. 28, 20 · Analysis
Likes (29)
Comment
Save
Tweet
Share
91.6K Views

Join the DZone community and get the full member experience.

Join For Free

As Java developers, we need to cover a lot of scenarios to ensure the quality of our software and catch bugs as soon as possible when introducing new code. For 99% of all my use cases, AssertJ, JUnit, Mockito, and Wiremock are sufficient enough to cover the test cases. But for the other use cases, like unit testing info, debugging or warning log messages, these frameworks don't help you out. There is also no other framework that can provide an easy to use method to capture log messages.

The answer which the community provided works well, but it needs a lot of boilerplate code to just assert your log events. So, I wanted to make it easier for myself and share it with you! This is how the LogCaptor library came into life.

Include the following dependency in your project as a test dependency:

XML
 




x


 
1
<dependency>
2
    <groupId>io.github.hakky54</groupId>
3
    <artifactId>logcaptor</artifactId>
4
    <version>2.3.1</version>
5
    <scope>test</scope>
6
</dependency>


Or get here the latest version: Maven Central

Let's assume you have the following service which creates logs:

Java
 




xxxxxxxxxx
1
13


 
1
import org.apache.logging.log4j.LogManager;
2
import org.apache.logging.log4j.Logger;
3

          
4
public class FooService {
5

          
6
    private static final Logger LOGGER = LogManager.getLogger(FooService.class);
7

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

          
13
}


Or the same service but with the SLF4J API logging facade:

Java
 




x


 
1
import org.slf4j.Logger;
2
import org.slf4j.LoggerFactory;
3

          
4
public class FooService {
5

          
6
    private static final Logger LOGGER = LoggerFactory.getLogger(ZooService.class);
7

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

          
13
}


Let's create a unit test for this service to assert the log messages and the log levels:

Java
 




x


 
1
import static org.assertj.core.api.Assertions.assertThat;
2
import org.junit.Test;
3

          
4
public class FooServiceShould {
5

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

          
11
        LogCaptor<FooService> logCaptor = LogCaptor.forClass(FooService.class);
12

          
13
        FooService fooService = new FooService();
14
        fooService.sayHello();
15

          
16
        assertThat(logCaptor.getInfoLogs().containsExactly(expectedInfoMessage);
17
        assertThat(logCaptor.getWarnLogs.containsExactly(expectedWarnMessage);
18
    }
19
}


You can also get all the log messages by discarding the log level:

Java
 




xxxxxxxxxx
1
20


 
1
import static org.assertj.core.api.Assertions.assertThat;
2
import org.junit.Test;
3

          
4
public class FooServiceShould {
5

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

          
11
        LogCaptor<FooService> logCaptor = LogCaptor.forClass(FooService.class);
12

          
13
        FooService fooService = new FooService();
14
        fooService.sayHello();
15

          
16
        assertThat(logCaptor.getLogs())
17
                .hasSize(2)
18
                .containsExactly(expectedInfoMessage, expectedWarnMessage);
19
    }
20
}


It is also possible to test certain log messages when the log level is enabled for a specific level; see the example snippet below:

Java
 




xxxxxxxxxx
1
15


 
1
import org.apache.logging.log4j.LogManager;
2
import org.apache.logging.log4j.Logger;
3

          
4
public class FooService {
5

          
6
    private static final Logger LOGGER = LogManager.getLogger(FooService.class);
7

          
8
    public void sayHello() {
9
        if (LOGGER.isDebugEnabled()) {
10
            LOGGER.debug("Keyboard not responding. Press any key to continue...");
11
        }
12
        LOGGER.info("Congratulations, you are pregnant!");
13
    }
14

          
15
}


In the the example unit test below, having only the info level enabled should log your debug messages:

Java
 




xxxxxxxxxx
1
24


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

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

          
6
public class FooServiceShould {
7

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

          
13
        LogCaptor<FooService> logCaptor = LogCaptor.forClass(FooService.class);
14
        logCaptor.setLogLevelToInfo();
15

          
16
        FooService fooService = new FooService();
17
        fooService.sayHello();
18

          
19
        assertThat(logCaptor.getInfoLogs()).containsExactly(expectedInfoMessage);
20
        assertThat(logCaptor.getDebugLogs())
21
            .doesNotContain(expectedDebugMessage)
22
            .isEmpty();
23
    }
24
}


The source code is available on GitHub with other examples: GitHub — Log Captor.

Get the latest version from Maven Central.

It also works with Lombok logging annotations, such as Log4j, Log4j2, Slf4j, and Log.

Good luck and enjoy asserting your log messages!

Further Reading

Unit Testing Guidelines: What to Test and What Not to Test

8 Benefits of Unit Testing

unit test Java (programming language) Log4j Boilerplate code

Opinions expressed by DZone contributors are their own.

Related

  • Finally, an ORM That Matches Modern Architectural Patterns!
  • The Hidden Costs of Lombok in Enterprise Java Solutions
  • Mastering Unit Testing and Test-Driven Development in Java
  • Comprehensive Guide to Unit Testing Spring AOP Aspects

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!