BAEL-1843 - JUnit4 -> JUnit5 migration guide (#4816)

* Added code for the migration from JUnit 4 to JUnit 5

* Add example for Rule migration support

* Add fix to access modifiers to test methods

* Remove wrong header

* Add junit5-migration module and its code snippets

* Add module configuration to pom

* Remove test classes that were added for the migration from JUnit 4 to JUnit 5 article (moved under correct module)
This commit is contained in:
Carlo Corti
2018-08-06 23:38:54 +02:00
committed by Grzegorz Piwowarek
parent b5d5a4949f
commit b7355cbab0
25 changed files with 656 additions and 9 deletions
@@ -0,0 +1,22 @@
package com.baeldung.junit4;
import com.baeldung.junit4.categories.Annotations;
import com.baeldung.junit4.categories.JUnit4UnitTest;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(value = { Annotations.class, JUnit4UnitTest.class })
public class AnnotationTestExampleUnitTest {
@Test(expected = Exception.class)
public void shouldRaiseAnException() throws Exception {
throw new Exception("This is my expected exception");
}
@Test(timeout = 1)
@Ignore
public void shouldFailBecauseTimeout() throws InterruptedException {
Thread.sleep(10);
}
}
@@ -0,0 +1,36 @@
package com.baeldung.junit4;
import org.junit.Assert;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.junit.Assert.*;
import static org.junit.Assert.assertArrayEquals;
@DisplayName("Test case for assertions")
public class AssertionUnitTest {
@Test
@DisplayName("Arrays should be equals")
public void whenAssertingArraysEquality_thenEqual() {
char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'};
char[] actual = "Jupiter".toCharArray();
assertArrayEquals("Arrays should be equal", expected, actual);
}
@Test
public void givenMultipleAssertion_whenAssertingAll_thenOK() {
assertEquals("4 is 2 times 2", 4, 2 * 2);
assertEquals("java", "JAVA".toLowerCase());
assertEquals("null is equal to null", null, null);
}
@Test
public void testAssertThatHasItems() {
assertThat(Arrays.asList("Java", "Kotlin", "Scala"), hasItems("Java", "Kotlin"));
}
}
@@ -0,0 +1,23 @@
package com.baeldung.junit4;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
public class AssumeUnitTest {
@Test
public void trueAssumption() {
assumeTrue("5 is greater the 1", 5 > 1);
assertEquals(5 + 2, 7);
}
@Test
public void falseAssumption() {
assumeFalse("5 is less then 1", 5 < 1);
assertEquals(5 + 2, 7);
}
}
@@ -0,0 +1,24 @@
package com.baeldung.junit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ExceptionAssertionUnitTest {
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Test(expected = NullPointerException.class)
public void whenExceptionThrown_thenExpectationSatisfied() {
String test = null;
test.length();
}
@Test
public void whenExceptionThrown_thenRuleIsApplied() {
exceptionRule.expect(NumberFormatException.class);
exceptionRule.expectMessage("For input string");
Integer.parseInt("1a");
}
}
@@ -0,0 +1,16 @@
package com.baeldung.junit4;
import org.junit.Rule;
import org.junit.Test;
public class RuleExampleUnitTest {
@Rule
public final TraceUnitTestRule traceRuleTests = new TraceUnitTestRule();
@Test
public void whenTracingTests() {
System.out.println("This is my test");
/*...*/
}
}
@@ -0,0 +1,34 @@
package com.baeldung.junit4;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import java.util.logging.Logger;
public class TestAnnotationsUnitTest {
private static final Logger log = Logger.getLogger(TestAnnotationsUnitTest.class.getName());
@BeforeClass
static void setup() {
log.info("@BeforeAll - executes once before all test methods in this class");
}
@Before
void init() {
log.info("@BeforeEach - executes before each test method in this class");
}
@After
void tearDown() {
log.info("@AfterEach - executed after each test method.");
}
@AfterClass
static void done() {
log.info("@AfterAll - executed after all test methods.");
}
}
@@ -0,0 +1,35 @@
package com.baeldung.junit4;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.MultipleFailureException;
import org.junit.runners.model.Statement;
import java.util.ArrayList;
import java.util.List;
public class TraceUnitTestRule implements TestRule {
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
List<Throwable> errors = new ArrayList<Throwable>();
System.out.println("Starting test ... " + description.getMethodName());
try {
base.evaluate();
} catch (Throwable e) {
errors.add(e);
} finally {
System.out.println("... test finished. " + description.getMethodName());
}
MultipleFailureException.assertEmpty(errors);
}
};
}
}
@@ -0,0 +1,5 @@
package com.baeldung.junit4.categories;
public interface Annotations {
}
@@ -0,0 +1,5 @@
package com.baeldung.junit4.categories;
public interface JUnit4UnitTest {
}
@@ -0,0 +1,28 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import java.time.Duration;
@Tag("annotations")
@Tag("junit5")
@RunWith(JUnitPlatform.class)
public class AnnotationTestExampleUnitTest {
@Test
public void shouldRaiseAnException() throws Exception {
Assertions.assertThrows(Exception.class, () -> {
throw new Exception("This is my expected exception");
});
}
@Test
@Disabled
public void shouldFailBecauseTimeout() throws InterruptedException {
Assertions.assertTimeout(Duration.ofMillis(1), () -> Thread.sleep(10));
}
}
@@ -0,0 +1,40 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DisplayName("Test case for assertions")
public class AssertionUnitTest {
@Test
@DisplayName("Arrays should be equals")
public void whenAssertingArraysEquality_thenEqual() {
char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'};
char[] actual = "Jupiter".toCharArray();
assertArrayEquals(expected, actual, "Arrays should be equal");
}
@Test
@DisplayName("The area of two polygons should be equal")
public void whenAssertingEquality_thenEqual() {
float square = 2 * 2;
float rectangle = 2 * 2;
assertEquals(square, rectangle);
}
@Test
public void givenMultipleAssertion_whenAssertingAll_thenOK() {
assertAll(
"heading",
() -> assertEquals(4, 2 * 2, "4 is 2 times 2"),
() -> assertEquals("java", "JAVA".toLowerCase()),
() -> assertEquals(null, null, "null is equal to null")
);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.*;
public class AssumptionUnitTest {
@Test
public void trueAssumption() {
assumeTrue(5 > 1, () -> "5 is greater the 1");
assertEquals(5 + 2, 7);
}
@Test
public void falseAssumption() {
assumeFalse(5 < 1, () -> "5 is less then 1");
assertEquals(5 + 2, 7);
}
@Test
public void assumptionThat() {
String someString = "Just a string";
assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4));
}
}
@@ -0,0 +1,69 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.*;
import static org.junit.jupiter.api.Assertions.*;
public class ConditionalExecutionUnitTest {
@Test
@EnabledOnOs({OS.MAC})
void whenOperatingSystemIsMac_thenTestIsEnabled() {
assertEquals(5 + 2, 7);
}
@Test
@DisabledOnOs({OS.WINDOWS})
void whenOperatingSystemIsWindows_thenTestIsDisabled() {
assertEquals(5 + 2, 7);
}
@Test
@EnabledOnJre({JRE.JAVA_8})
void whenRunningTestsOnJRE8_thenTestIsEnabled() {
assertTrue(5 > 4, "5 is greater the 4");
assertTrue(null == null, "null is equal to null");
}
@Test
@DisabledOnJre({JRE.JAVA_10})
void whenRunningTestsOnJRE10_thenTestIsDisabled() {
assertTrue(5 > 4, "5 is greater the 4");
assertTrue(null == null, "null is equal to null");
}
@Test
@EnabledIfSystemProperty(named = "os.arch", matches = ".*64.*")
public void whenRunningTestsOn64BitArchitectures_thenTestIsDisabled() {
Integer value = 5; // result of an algorithm
assertNotEquals(0, value, "The result cannot be 0");
}
@Test
@DisabledIfSystemProperty(named = "ci-server", matches = "true")
public void whenRunningTestsOnCIServer_thenTestIsDisabled() {
Integer value = 5; // result of an algorithm
assertNotEquals(0, value, "The result cannot be 0");
}
@Test
@EnabledIfEnvironmentVariable(named = "ENV", matches = "staging-server")
public void whenRunningTestsStagingServer_thenTestIsEnabled() {
char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'};
char[] actual = "Jupiter".toCharArray();
assertArrayEquals(expected, actual, "Arrays should be equal");
}
@Test
@DisabledIfEnvironmentVariable(named = "ENV", matches = ".*development.*")
public void whenRunningTestsDevelopmentEnvironment_thenTestIsDisabled() {
char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'};
char[] actual = "Jupiter".toCharArray();
assertArrayEquals(expected, actual, "Arrays should be equal");
}
}
@@ -0,0 +1,77 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.*;
import java.util.EmptyStackException;
import java.util.Stack;
public class NestedUnitTest {
Stack<Object> stack;
@Test
@DisplayName("is instantiated with new Stack()")
void isInstantiatedWithNew() {
new Stack<>();
}
@Nested
@DisplayName("when new")
class WhenNew {
@BeforeEach
void init() {
stack = new Stack<>();
}
@Test
@DisplayName("is empty")
void isEmpty() {
Assertions.assertTrue(stack.isEmpty());
}
@Test
@DisplayName("throws EmptyStackException when popped")
void throwsExceptionWhenPopped() {
Assertions.assertThrows(EmptyStackException.class, () -> stack.pop());
}
@Test
@DisplayName("throws EmptyStackException when peeked")
void throwsExceptionWhenPeeked() {
Assertions.assertThrows(EmptyStackException.class, () -> stack.peek());
}
@Nested
@DisplayName("after pushing an element")
class AfterPushing {
String anElement = "an element";
@BeforeEach
void init() {
stack.push(anElement);
}
@Test
@DisplayName("it is no longer empty")
void isEmpty() {
Assertions.assertFalse(stack.isEmpty());
}
@Test
@DisplayName("returns the element when popped and is empty")
void returnElementWhenPopped() {
Assertions.assertEquals(anElement, stack.pop());
Assertions.assertTrue(stack.isEmpty());
}
@Test
@DisplayName("returns the element when peeked but remains not empty")
void returnElementWhenPeeked() {
Assertions.assertEquals(anElement, stack.peek());
Assertions.assertFalse(stack.isEmpty());
}
}
}
}
@@ -0,0 +1,17 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
@ExtendWith(TraceUnitExtension.class)
public class RuleExampleUnitTest {
@Test
public void whenTracingTests() {
System.out.println("This is my test");
/*...*/
}
}
@@ -0,0 +1,27 @@
package com.baeldung.junit5;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.rules.ExpectedException;
@EnableRuleMigrationSupport
public class RuleMigrationSupportUnitTest {
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Test
public void whenExceptionThrown_thenExpectationSatisfied() {
exceptionRule.expect(NullPointerException.class);
String test = null;
test.length();
}
@Test
public void whenExceptionThrown_thenRuleIsApplied() {
exceptionRule.expect(NumberFormatException.class);
exceptionRule.expectMessage("For input string");
Integer.parseInt("1a");
}
}
@@ -0,0 +1,39 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.*;
import java.util.logging.Logger;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestAnnotationsUnitTest {
private static final Logger log = Logger.getLogger(TestAnnotationsUnitTest.class.getName());
@BeforeAll
static void setup() {
log.info("@BeforeAll - executes once before all test methods in this class");
}
@BeforeEach
void init() {
log.info("@BeforeEach - executes before each test method in this class");
}
@Test
@Disabled
void disabledTest() {
assertTrue(false);
}
@AfterEach
void tearDown() {
log.info("@AfterEach - executed after each test method.");
}
@AfterAll
static void done() {
log.info("@AfterAll - executed after all test methods.");
}
}
@@ -0,0 +1,19 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
public class TraceUnitExtension implements AfterEachCallback, BeforeEachCallback {
@Override
public void beforeEach(ExtensionContext context) throws Exception {
System.out.println("Starting test ... " + context.getDisplayName());
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
System.out.println("... test finished. " + context.getDisplayName());
}
}