Skip to content

Commit

Permalink
Merge pull request #5 from dm-drogeriemarkt/junit5
Browse files Browse the repository at this point in the history
Junit5
  • Loading branch information
waschmittel authored Mar 16, 2020
2 parents 0e65ff5 + 87f1f03 commit 71016cd
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 57 deletions.
25 changes: 20 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
[<img src="https://opensourcelogos.aws.dmtech.cloud/dmTECH_opensource_logo.svg" height="20" width="130">](https://dmtech.de/)
[![Build Status](https://travis-ci.org/dm-drogeriemarkt/log-capture.svg?branch=master)](https://travis-ci.org/dm-drogeriemarkt/log-capture)

Helper for Unit/Integration tests with JUnit 4 to test if something has been logged.
Helper for Unit/Integration tests with JUnit 4/5 to test if something has been logged.

Because this is a library, Checkstyle is used to make sure all public classes/methods have appropriate Javadoc.

Expand All @@ -24,6 +24,15 @@ Because this is a library, Checkstyle is used to make sure all public classes/me

## Changes

### 3.0.0

Updated from JUnit 4 to JUnit 5.

To update from 2.x.x to 3.x.x:

* Use JUnit 5 instead of JUnit 4
* Replace `@Rule` in logging tests with `@RegisterExtension`

### 2.0.1

Fixed a bug where multiline log messages (for example Messages that contain a stack trace) could not be matched.
Expand All @@ -37,6 +46,12 @@ Fixed a bug where multiline log messages (for example Messages that contain a st

## Usage

### Junit 4 vs 5

If you still use Junit 4, you need to use LogCapture 2.x.x

There is no guarantee, however, if and how long 2.x.x will be maintained. We plan to maintain it as long as it is needed, though.

### Maven

Add log-capture as a test dependency to your project. If you use Maven, add this to your pom.xml:
Expand All @@ -45,7 +60,7 @@ Add log-capture as a test dependency to your project. If you use Maven, add this
<dependency>
<groupId>de.dm.infrastructure</groupId>
<artifactId>log-capture</artifactId>
<version>2.0.1</version>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
```
Expand All @@ -64,7 +79,7 @@ public class MyUnitTest {

Logger logger = LoggerFactory.getLogger(MyUnitTest.class);

@Rule
@RegisterExtension //use @Rule for LogCapture 2/JUnit 4
public LogCapture logCapture = LogCapture.forCurrentPackage();

@Test
Expand Down Expand Up @@ -94,7 +109,7 @@ public class MyIntegrationTest {
Logger logger = LoggerFactory.getLogger(MyIntegrationTest.class);

// captures only logs from my.company and utility.that.logs and sub-packages
@Rule
@RegisterExtension //use @Rule for LogCapture 2/JUnit 4
public LogCapture logCapture = LogCapture.forPackages("my.company", "utility.that.logs");

@Test
Expand Down Expand Up @@ -127,7 +142,7 @@ import static de.dm.prom.logcapture.ExpectedMdcEntry.withMdc;
public class MyUnitTest {
Logger logger = LoggerFactory.getLogger(MyUnitTest.class);

@Rule
@RegisterExtension
public LogCapture logCapture = LogCapture.forCurrentPackage();

@Test
Expand Down
23 changes: 14 additions & 9 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,18 @@

<properties>
<java.version>1.8</java.version>
<lombok.version>1.18.10</lombok.version>
<lombok.version>1.18.12</lombok.version>
<logback.version>1.2.3</logback.version>
<junit.version>4.12</junit.version>
<junit.version>5.6.0</junit.version>
<encoding>UTF-8</encoding>

<assertj-core.version>3.14.0</assertj-core.version>
<checkstyle.version>8.29</checkstyle.version>
<assertj-core.version>3.15.0</assertj-core.version>
<checkstyle.version>8.30</checkstyle.version>
<jacoco.version>0.8.5</jacoco.version>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<maven-checkstyle-plugin.version>3.1.0</maven-checkstyle-plugin.version>
<maven-source-plugin.version>3.1.0</maven-source-plugin.version>
<maven-javadoc-plugin.version>3.1.1</maven-javadoc-plugin.version>
<maven-checkstyle-plugin.version>3.1.1</maven-checkstyle-plugin.version>
<maven-source-plugin.version>3.2.1</maven-source-plugin.version>
<maven-javadoc-plugin.version>3.2.0</maven-javadoc-plugin.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<maven-release-plugin.version>2.5.3</maven-release-plugin.version>
<maven-gpg-plugin.version>1.6</maven-gpg-plugin.version>
Expand All @@ -61,8 +61,13 @@
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
Expand Down
17 changes: 17 additions & 0 deletions rules.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<ruleset xmlns="http://mojo.codehaus.org/versions-maven-plugin/rule/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" comparisonMethod="maven"
xsi:schemaLocation="http://mojo.codehaus.org/versions-maven-plugin/rule/2.0.0 http://mojo.codehaus.org/versions-maven-plugin/xsd/rule-2.0.0.xsd">
<ignoreVersions>
<!-- Ignore Alpha's, Beta's, release candidates and milestones -->
<ignoreVersion type="regex">(?i).*Alpha(?:-?\d+)?</ignoreVersion>
<ignoreVersion type="regex">(?i).*a(?:-?\d+)?</ignoreVersion>
<ignoreVersion type="regex">(?i).*Beta(?:-?\d+)?</ignoreVersion>
<ignoreVersion type="regex">(?i).*-B(?:-?\d+)?</ignoreVersion>
<ignoreVersion type="regex">(?i).*RC(?:-?\d+)?</ignoreVersion>
<ignoreVersion type="regex">(?i).*CR(?:-?\d+)?</ignoreVersion>
<ignoreVersion type="regex">(?i).*M(?:-?\d+)?</ignoreVersion>
</ignoreVersions>
<rules>
</rules>
</ruleset>
27 changes: 11 additions & 16 deletions src/main/java/de/dm/infrastructure/logcapture/LogCapture.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import lombok.RequiredArgsConstructor;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
Expand All @@ -16,7 +16,7 @@
/**
* a JUnit 4 @Rule that can be used to capture log output. Use the appropriate constructor for unit/integration tests.
*/
public final class LogCapture implements TestRule { //should implement AfterEachCallback, BeforeEachCallback in JUnit 5
public final class LogCapture implements BeforeEachCallback, AfterEachCallback { //should implement AfterEachCallback, BeforeEachCallback in JUnit 5

final Set<String> capturedPackages;
private CapturingAppender capturingAppender;
Expand Down Expand Up @@ -59,18 +59,13 @@ private LogCapture(Set<String> capturedPackages) {
}

@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
addAppenderAndSetLogLevelToDebug();
try {
base.evaluate();
} finally {
removeAppenderAndResetLogLevel();
}
}
};
public void beforeEach(ExtensionContext context) {
addAppenderAndSetLogLevelToDebug();
}

@Override
public void afterEach(ExtensionContext context) {
removeAppenderAndResetLogLevel();
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package de.dm.infrastructure.logcapture;

import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;
Expand All @@ -21,12 +21,12 @@ public void containsMdcEntries() {
mdcContents.put(TEST_KEY, "this is a test value, cool!");
mdcContents.put(OTHER_KEY, "this is a good value, cool!");

Assert.assertTrue(CapturingAppender.containsMdcEntries(mdcContents, expectedMdcEntries));
Assertions.assertTrue(CapturingAppender.containsMdcEntries(mdcContents, expectedMdcEntries));
}

@Test
public void nullEntriesShouldNotThrowNullPointerException() {
Map<String, String> mdcContents = new HashMap<>();
Assert.assertTrue(CapturingAppender.containsMdcEntries(mdcContents, null));
Assertions.assertTrue(CapturingAppender.containsMdcEntries(mdcContents, null));
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package de.dm.infrastructure.logcapture;

import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;
Expand All @@ -15,7 +15,7 @@ public void isContainedIn() {
ExpectedMdcEntry expectedMdcEntry = ExpectedMdcEntry.withMdc(TEST_KEY, "test value");
Map<String, String> mdcContents = new HashMap<>();
mdcContents.put(TEST_KEY, "this is a test value, cool!");
Assert.assertTrue(expectedMdcEntry.isContainedIn(mdcContents));
Assertions.assertTrue(expectedMdcEntry.isContainedIn(mdcContents));
}

@Test
Expand All @@ -24,7 +24,7 @@ public void isNotContainedIn() {
Map<String, String> mdcContents = new HashMap<>();
mdcContents.put(TEST_KEY, "this is a value, cool!");
mdcContents.put("some_other_key", "this is a test value, cool!");
Assert.assertFalse(expectedMdcEntry.isContainedIn(mdcContents));
Assertions.assertFalse(expectedMdcEntry.isContainedIn(mdcContents));
}

}
54 changes: 35 additions & 19 deletions src/test/java/de/dm/infrastructure/logcapture/LogCaptureTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import ch.qos.logback.classic.Level;
import com.example.app.LogCaptureCreatorInOtherPackage;
import lombok.extern.slf4j.Slf4j;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
Expand All @@ -18,11 +18,11 @@
@Slf4j
public class LogCaptureTest {

@Rule
@RegisterExtension
public LogCapture logCapture = LogCapture.forPackages("de.dm", "com.capture");

@Rule //to be replaced with Assertions.assertThrows() in JUnit 5
public final ExpectedException exception = ExpectedException.none();
@RegisterExtension
public LogCapture logCaptureForCurrentPackage = LogCapture.forCurrentPackage();

@Test
public void twoLogMessagesInOrder() {
Expand All @@ -41,6 +41,21 @@ public void captureMultilineMessages() {
logCapture.assertLogged(Level.INFO, "something interesting");
}

@Test
public void captureLogsForCurrentPackage() {
log.info("Hello from logcapture");

final Logger acmeLogger = LoggerFactory.getLogger("com.acme");
acmeLogger.info("Hello from com.acme");

logCaptureForCurrentPackage
.assertLogged(INFO, "^Hello from logcapture$");

Assertions.assertThrows(AssertionError.class, () -> {
logCaptureForCurrentPackage.assertLogged(INFO, "Hello from com.acme");
});
}

@Test
public void captureLogsForMultiplePackages() {
log.info("something interesting");
Expand All @@ -57,14 +72,14 @@ public void captureLogsForMultiplePackages() {

@Test
public void twoLogMessagesOutOfOrder() {
log.error("something terrible");
log.info("something interesting");

exception.expect(AssertionError.class);
Assertions.assertThrows(AssertionError.class, () -> {
log.error("something terrible");
log.info("something interesting");

logCapture
.assertLogged(Level.INFO, "^something interesting")
.thenLogged(Level.ERROR, "terrible");
logCapture
.assertLogged(Level.INFO, "^something interesting")
.thenLogged(Level.ERROR, "terrible");
});
}

@Test
Expand All @@ -84,12 +99,13 @@ public void catchMissingLogMessage() {

@Test
public void filterOutIrrelevantLogMessagesInIntegrationTest() {
ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
rootLogger.getLoggerContext().getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).setLevel(DEBUG);
Logger logger = LoggerFactory.getLogger("com.acme.whatever");
logger.info("something from another package");
exception.expect(AssertionError.class);
logCapture.assertLogged(Level.INFO, "something from another package");
Assertions.assertThrows(AssertionError.class, () -> {
ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
rootLogger.getLoggerContext().getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).setLevel(DEBUG);
Logger logger = LoggerFactory.getLogger("com.acme.whatever");
logger.info("something from another package");
logCapture.assertLogged(Level.INFO, "something from another package");
});
}

@Test
Expand Down

0 comments on commit 71016cd

Please sign in to comment.