BAEL-2947 - Guide to Junit 4 Rules

This commit is contained in:
Jon Cook 2019-08-12 13:37:48 +02:00
parent f918e37fa6
commit 7d1499f5c3
8 changed files with 237 additions and 0 deletions

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>junit-4</artifactId>
<version>1.0-SNAPSHOT</version>
<name>junit-4</name>
<description>JUnit 4 Topics</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
</project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,34 @@
package com.baeldung.rules;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MessageLogger implements TestRule {
private static final Logger LOG = LoggerFactory.getLogger(MessageLogger.class);
private String message;
public MessageLogger(String message) {
this.message = message;
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
LOG.info("Starting: {}", message);
base.evaluate();
} finally {
LOG.info("Finished: {}", message);
}
}
};
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.rules;
import static org.junit.Assert.assertTrue;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
public class RuleChainUnitTest {
@Rule
public RuleChain chain = RuleChain.outerRule(new MessageLogger("First rule"))
.around(new MessageLogger("Second rule"))
.around(new MessageLogger("Third rule"));
@Test
public void givenRuleChain_whenTestRuns_thenChainOrderApplied() {
assertTrue(true);
}
}

View File

@ -0,0 +1,88 @@
package com.baeldung.rules;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.isA;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.ErrorCollector;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestName;
import org.junit.rules.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RulesUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(RulesUnitTest.class);
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule
public TestName name = new TestName();
@Rule
public Timeout globalTimeout = Timeout.seconds(10);
@Rule
public final ErrorCollector errorCollector = new ErrorCollector();
@Rule
public DisableOnDebug disableTimeout = new DisableOnDebug(Timeout.seconds(30));
@Rule
public TestMethodNameLogger testLogger = new TestMethodNameLogger();
@Test
public void givenTempFolderRule_whenNewFile_thenFileIsCreated() throws IOException {
File testFile = tmpFolder.newFile("test-file.txt");
assertTrue("The file should have been created: ", testFile.isFile());
assertEquals("Temp folder and test file should match: ", tmpFolder.getRoot(), testFile.getParentFile());
}
@Test
public void givenIllegalArgument_whenExceptionThrown_thenMessageAndCauseMatches() {
thrown.expect(IllegalArgumentException.class);
thrown.expectCause(isA(NullPointerException.class));
thrown.expectMessage("This is illegal");
throw new IllegalArgumentException("This is illegal", new NullPointerException());
}
@Test
public void givenAddition_whenPrintingTestName_thenTestNameIsDisplayed() {
LOG.info("Executing: {}", name.getMethodName());
assertEquals("givenAddition_whenPrintingTestName_thenTestNameIsDisplayed", name.getMethodName());
}
@Ignore
@Test
public void givenLongRunningTest_whenTimout_thenTestFails() throws InterruptedException {
TimeUnit.SECONDS.sleep(20);
}
@Ignore
@Test
public void givenMultipleErrors_whenTestRuns_thenCollectorReportsErrors() {
errorCollector.addError(new Throwable("First thing went wrong!"));
errorCollector.addError(new Throwable("Another thing went wrong!"));
errorCollector.checkThat("Hello World", not(containsString("ERROR!")));
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.rules;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestMethodNameLogger implements TestRule {
private static final Logger LOG = LoggerFactory.getLogger(TestMethodNameLogger.class);
@Override
public Statement apply(Statement base, Description description) {
logInfo("Before test", description);
try {
return new Statement() {
@Override
public void evaluate() throws Throwable {
base.evaluate();
}
};
} finally {
logInfo("After test", description);
}
}
private void logInfo(String msg, Description description) {
LOG.info(msg + description.getMethodName());
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.rules;
import static org.junit.Assert.assertFalse;
import java.util.ArrayList;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Verifier;
public class VerifierRuleUnitTest {
private List<String> messageLog = new ArrayList<String>();
@Rule
public Verifier verifier = new Verifier() {
@Override
public void verify() {
assertFalse("Message Log is not Empty!", messageLog.isEmpty());
}
};
@Test
public void givenNewMessage_whenVerified_thenMessageLogNotEmpty() {
// ...
messageLog.add("There is a new message!");
}
}

View File

@ -37,5 +37,6 @@
<module>easymock</module>
<module>junit-5-advanced</module>
<module>xmlunit-2</module>
<module>junit-4</module>
</modules>
</project>