JUnit 5 Unit Testing Guide
JUnit 5 Unit Testing Guide
8. Exercise: Develop unit tests for a regular expression utility method for email verification
13. Exercise: Using the @TempDir annotation to create temporary files and paths
16. Exercise: Clone the JUnit5 Github repo and review tests
18. Conclusion
This tutorial explains unit testing with JUnit with the JUnit 5 framework (JUnit Jupiter). It
explains the creation of JUnit 5 tests with the Maven and Gradle build system. It
demonstrates the usage of the Eclipse IDE for developing software tests with JUnit 5 but this
tutorial is also valid for tools like Visual Code or IntelliJ.
([Link]
1. Overview
JUnit is a popular unit-testing framework in the Java ecosystem. JUnit 5 added many new features based on
the Java 8 version of the language.
This guide gives an introduction into unit testing with the JUnit framework using JUnit 5. It focus on the usage
of the framework.
[Link] 1/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
Using Maven
Company ([Link] in the
Contact usEclipse IDE ([Link]
([Link]
GET MORE...
Using the Eclipse IDE for creating and running JUnit test
Read Premium Content ...
([Link]
([Link]
Using Gradle in the Eclipse IDE ([Link]
Book Onsite or Virtual Training
Mockito tutorial ([Link] ([Link]
The following code defines a minimal test class with one minimal test method.
JAVA
package [Link];
import [Link];
class AClassWithOneJUnitTest {
@Test
void demoTestMethod() {
assertTrue(true);
}
}
You can use assert methods, provided by JUnit or another assert framework, to check an expected result
versus the actual result. Such statement are called asserts or assert statements.
Assert statements typically allow to define messages which are shown if the test fails. You should provide
here meaningful messages to make it easier for the user to identify and fix the problem. This is especially true
if someone looks at the problem, who did not write the code under test or the test code.
Assume you have the following class which you want to test.
ⓘ
([Link]
id0348293521d)
[Link] 2/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
package [Link].junit5;
Tutorials ([Link] Training ([Link] Consulting ([Link]
([Link] public class Calculator {
A test class for the above class could look like the following.
Book Onsite or Virtual Training
([Link]
package [Link].junit5;
Consulting JAVA
([Link]
import static [Link];
Calculator calculator;
@BeforeEach 1
void setUp() {
calculator = new Calculator();
}
@Test 2
void testMultiply() {
assertEquals(20, [Link](4, 5), 4
@RepeatedTest(5) 6
4 This is an assert statement which validates that expected and actual value is the same, if not the
message at the end of the method is shown
5 @RepeatedTest defines that this test method will be executed multiple times, in this example 5 times
**/Test*.java 1
**/*[Link] 2
**/*[Link] 3
**/*[Link] 4
1 includes all of its subdirectories and all Java filenames that start with Test .
2 includes all of its subdirectories and all Java filenames that end with Test .
3 includes all of its subdirectories and all Java filenames that end with Tests .
4 includes all of its subdirectories and all Java filenames that end with TestCase .
Therefore, it is common practice to use the Test or Tests suffix at the end of test classes names.
[Link] 3/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
Messages can be created via lambda expressions, to avoid the overhead in case the construction of the
message is expensive.
JAVA
assertTrue('a' < 'b', () -> "Assertion messages can be lazily evaluated -- "
+ "to avoid constructing complex messages unnecessarily.");
JAVA
import static [Link];
@Test
void exceptionTesting() {
// set up user
Throwable exception = assertThrows([Link], () ->
[Link]("23"));
assertEquals("Age must be an Integer.", [Link]());
}
This lets you define which part of the test should throw the exception. The test will still fail if an exception is
thrown outside of this scope.
[Link] 4/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
import static [Link];
import static [Link];
import static [Link];
@Test
void timeoutNotExceeded() {
assertTimeout(ofMinutes(1), () -> [Link]());
}
JAVA
=> [Link]: execution exceeded timeout of 1000 ms by 212 ms
If you want your tests to cancel after the timeout period is passed you can use the
assertTimeoutPreemptively() method.
JAVA
@Test
void timeoutNotExceededWithResult() {
String actualResult = assertTimeoutPreemptively(ofSeconds(1), () -> {
return [Link](request);
});
assertEquals(200, [Link]());
}
JAVA
=> [Link]: execution timed out after 1000 ms
Such a test might be flacky, in case the test server is busy, the test execution might take
longer and therefore such a test might fails from time to time.
[Link] 5/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
package [Link].junit5;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@BeforeEach
void setUp() throws Exception {
calculator = new Calculator();
}
@RepeatedTest(5)
@DisplayName("Ensure correct handling of zero")
void testMultiplyWithZero() {
[Link]([Link]("[Link]").contains("Linux"));
You can also write an extension for @ExtendWith which defines conditions under which a test should run.
an Iterable
a Collection
a Stream
JUnit 5 creates and runs all dynamic tests during test execution.
[Link] 6/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
Methods annotated with @BeforeEach and @AfterEach are not called for dynamic tests. This means, that
Tutorials ([Link] Training
you can’t use thesm ([Link]
to reset Consulting
the test object, if you change it’s state ([Link]
in the lambda expression for a dynamic
([Link] test.
Company ([Link] Contact us ([Link]
GETinstances.
In the following example we define a method to return a Stream of DynamicTest MORE...
Read Premium Content ...
JAVA
package [Link];
([Link]
import static [Link]; Book Onsite or Virtual Training
import static [Link];
([Link]
import [Link]; Consulting
import [Link];
([Link]
import [Link];
import [Link]; TRAINING EVENTS
class DynamicTestCreationTest { Now offering virtual, onsite and
online training
@TestFactory
Stream<DynamicTest> testDifferentMultiplyOperations() { ([Link]
MyClass tester = new MyClass();
int[][] data = new int[][] { { 1, 2, 2 }, { 5, 3, 15 }, { 121, 4, 484 } };
return [Link](data).map(entry -> {
int m1 = entry[0];
int m2 = entry[1];
int expected = entry[2];
return dynamicTest(m1 + " * " + m2 + " = " + expected, () -> {
assertEquals(expected, [Link](m1, m2));
});
});
}
// class to be tested
class MyClass {
public int multiply(int i, int j) {
return i * j;
}
}
}
We give it the name of the function(s) we want it to call to get it’s test data. The function has to be static and
must return either a Collection, an Iterator, a Stream or an Array. On execution the test method gets called once
for every entry in the data source. In contrast to Dynamic Tests @BeforeEach and @AfterEach methods
will be called for parameterized tests.
[Link] 7/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
import static [Link].*;
Tutorials ([Link] Training ([Link]
import [Link]; Consulting ([Link]
([Link] import [Link];
Annotation Description
@MethodSource(names = "genTestData")
JAVA
The result of the named method
is passed as argument to the
test.
@ArgumentsSource([Link])
JAVA
Specifies a class that provides
the test data. The referenced
class has to implement the
ArgumentsProvider interface.
If you need explicit conversion you can specify a converter with the @ConvertWith annotation. To define
your own converter you have to implement the ArgumentConverter interface. In the following example we
use the abstract SimpleArgumentConverter base class.
[Link] 8/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
@ParameterizedTest
Tutorials ([Link] Training
@ValueSource(ints ([Link]
= {1, 12, 42}) Consulting ([Link]
([Link] void testWithExplicitArgumentConversion(@ConvertWith([Link])
String argument) {
Company ([Link] Contact us ([Link]
[Link](argument);
assertNotNull(argument); GET MORE...
}
Read Premium Content ...
([Link]
static class ToOctalStringArgumentConverter extends SimpleArgumentConverter {
@Override
Book Onsite or Virtual Training
protected Object convert(Object source, Class<?> targetType) {
assertEquals([Link], [Link](), "Can only convert ([Link]
from Integers.");
assertEquals([Link], targetType, "Can only convert to String");
Consulting
return [Link]((Integer) source);
} ([Link]
}
TRAINING EVENTS
Now offering virtual, onsite and
online training
([Link]
ⓘ
([Link]
id0348293521d)
4. Additional information about JUnit 5 usage
4.1. Nested tests
The @Nested annotation can be used to annotate inner classes which also contain tests. This allows to
group tests and have additional @BeforeEach method, and one @AfterEach methods. When you add
nested test classes to our test class, the following rules must be followed:
The nested test classes are annotated with @Nested annotation so that the runtime can recognize the
nested test classes.
a nested test class can contain Test methods, one @BeforeEach method, and one @AfterEach method.
Because Java doesn’t allow static members in inner classes, a nested class cannot have
additional @BeforeAll and @AfterAll methods. There is no limit for the depth of the class
hierarchy.
Custom implementation - Implement your own MethodOrderer via the orderMethods method, which allows
you to call [Link]().sort(..)
[Link] 9/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
package [Link];
Tutorials ([Link] Training ([Link] Consulting ([Link]
([Link] import [Link];
import [Link];
Company ([Link]
import Contact us ([Link]
[Link];
import [Link]; GET MORE...
Read Premium Content ...
@TestMethodOrder([Link])
class OrderAnnotationDemoTest { ([Link]
Book Onsite or Virtual Training
@Test
@Order(1) ([Link]
void firstOne() {
Consulting
// test something here
} ([Link]
@Test
TRAINING EVENTS
@Order(2)
void secondOne() { Now offering virtual, onsite and
// test something here
} online training
([Link]
}
4.3. Using the @TempDir annotation to create temporary files and paths
The @TempDir annotations allows to annotate non-private fields or method parameters in a test method of
type Path or File. JUnit 5 has registered a `ParameterResolutionException for this
annotation and will create temporary files and paths for the tests. It will also remove the temporary files are
each test.
JAVA
@Test
@DisplayName("Ensure that two temporary directories with same files names and content
have same hash")
void hashTwoDynamicDirectoryWhichHaveSameContent(@TempDir Path tempDir, @TempDir Path
tempDir2) throws IOException {
[Link](file2, input);
assertTrue([Link](file2), "File should exist");
JAVA
import [Link];
import [Link];
import [Link];
@Suite
@SuiteDisplayName("JUnit Platform Suite Demo")
@SelectPackages("example")
public class SuiteDemo {
}
At this time of writing you can use the milestone release of 5.8.0-M1 to check this. See the dependencies here
[Link]
[Link] 10/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
Packaging: jar
Consulting
([Link]
5.2. Configure Maven dependencies for JUnit 5
TRAINING EVENTS
5.2.1. Steps required to configure Maven to use JUnit5
Now offering virtual, onsite and
To use JUnit5 in an Maven project, you need to:
online training
([Link]
Configure to use Java 11 or higher, as this is required by JUnit5
Configure the maven-surefire-plugin and maven-failsafe-plugin to be at version 2.22.2 so that they can run
JUnit5
Add dependencies to the JUnit5 API and engine for your test code
XML
<properties>
<[Link]>UTF-8</[Link]>
<[Link]>11</[Link]>
<[Link]>11</[Link]>
</properties>
<!--1 -->
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<!--2 -->
<dependencies>
<!-- [Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
</dependencies>
Once you have done this, you can start using JUnit5 in your Maven project for writing unit tests.
5.2.3. Update Maven settings (in case you are using the Eclipse IDE)
Right-click your pom file, select Maven Update Project and select your project. This triggers an update of your
project settings and dependencies.
[Link] 11/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
Alternatively you can right-click on your new class in the :_Project Explorer_ or Package
Explorer view and select New Other Java JUnit Test Case.
In the following wizard ensure that the New JUnit Jupiter test flag is selected. The source folder should select
the test directory.
[Link] 12/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
Press the Next button and select the methods that you want to test.
Tutorials ([Link] Training ([Link] Consulting ([Link]
([Link]
TRAINING EVENTS
Now offering virtual, onsite and
online training
([Link]
JAVA
package [Link];
import [Link];
import [Link];
class MyClassTest {
@Test
void testExceptionIsThrown() {
MyClass tester = new MyClass();
assertThrows([Link], () -> [Link](1000, 5));
}
@Test
void testMultiply() {
MyClass tester = new MyClass();
assertEquals(50, [Link](10, 5), "10 x 5 must be 50");
}
}
[Link] 13/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
The result of the tests are displayed in the JUnit view. In our example one test should be successful and one
Tutorials ([Link] Training
test should show an error.([Link]
This error is indicated by a red bar. Consulting ([Link]
([Link]
TRAINING EVENTS
Now offering virtual, onsite and
online training
([Link]
Solution
5.8. Review
After a few minutes you should have created a new project, a new class and a new unit test. Congratulations! If
you feel like it, lets improve the tests a bit and write one grouped test.
Solution
Solution
[Link] 14/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
mins
Tutorials ([Link] Training ([Link] Consulting ([Link]
([Link] In this exercise you learn you to write a JUnit5 test using the Gradle build system and the Eclipse IDE.
TRAINING and
The wizard should also have create the package [Link] in the src/main/java EVENTS
src/main/test
folder. Remove the generated classes from it.
Now offering virtual, onsite and
Modify your [Link] file to contain at least the following entries. Your build file may contain more
dependencies.
GRADLE
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
testImplementation '[Link]:junit-jupiter:5.7.2'
}
test {
useJUnitPlatform()
JAVA
package [Link];
Alternatively you can right-click on your new class in the :_Project Explorer_ or Package
Explorer view and select New Other Java JUnit Test Case.
In the following wizard ensure that the New JUnit Jupiter test flag is selected. The source folder should select
the test directory.
[Link] 15/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
TRAINING EVENTS
Now offering virtual, onsite and
online training
([Link]
Press the Next button and select the methods that you want to test.
[Link] 16/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
TRAINING EVENTS
Now offering virtual, onsite and
online training
([Link]
JAVA
package [Link];
import [Link];
import [Link];
class MyClassTest {
@Test
void testExceptionIsThrown() {
MyClass tester = new MyClass();
assertThrows([Link], () -> [Link](1000, 5));
}
@Test
void testMultiply() {
MyClass tester = new MyClass();
assertEquals(50, [Link](10, 5), "10 x 5 must be 50");
}
}
The result of the tests are displayed in the JUnit view. In our example one test should be successful and one
test should show an error. This error is indicated by a red bar.
[Link] 17/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
TRAINING EVENTS
Now offering virtual, onsite and
online training
([Link]
Solution
6.7. Review
After a few minutes you should have created a new project, a new class and a new unit test. Congratulations! If
you feel like it, lets improve the tests a bit and write one grouped test.
Solution
Solution
[Link] 18/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
7.2. Create the data model used for testing TRAINING EVENTS
Create the [Link] package and copy and paste the following classes on it.
Now offering virtual, onsite and
online training JAVA
package [Link];
([Link]
import [Link];
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((releaseDate == null) ? 0 : [Link]());
result = prime * result + ((title == null) ? 0 : [Link]());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != [Link]()) return false;
Movie other = (Movie) obj;
if (releaseDate == null) {
if ([Link] != null) return false;
} else if () return false;
if (title == null) {
if ([Link] != null) return false;
} else if () return false;
return true;
}
JAVA
package [Link];
[Link] 19/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
package [Link];
Tutorials ([Link] Training ([Link] Consulting ([Link]
([Link] import [Link];
import [Link];
Company ([Link]
import Contact us ([Link]
[Link];
import [Link]; GET MORE...
@Target([Link])
Read Premium Content ...
@Retention([Link]) ([Link]
public @interface Magical {
Book Onsite or Virtual Training
} ([Link]
Consulting
([Link]
JAVA
package [Link];
TRAINING EVENTS
/** Now offering virtual, onsite and
* Race in Tolkien's Lord of the Rings. online training
*
* @author Florent Biville ([Link]
*/
public enum Race {
@Override
public String toString() {
return "Race [name=" + name + ", immortal=" + immortal + "]";
}
}
JAVA
package [Link];
@Magical
public enum Ring {
oneRing, vilya, nenya, narya, dwarfRing, manRing;
[Link] 20/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
package [Link];
Tutorials ([Link] Training ([Link] Consulting ([Link]
([Link] public class TolkienCharacter {
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : [Link]());
result = prime * result + ((race == null) ? 0 : [Link]());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != [Link]()) return false;
TolkienCharacter other = (TolkienCharacter) obj;
if (age != [Link]) return false;
if (name == null) {
if ([Link] != null) return false;
} else if () return false;
if (race == null) {
if ([Link] != null) return false;
} else if () return false;
return true;
}
@Override
public String toString() {
return name + " " + age + " years old " + [Link]();
}
Create the [Link] package and copy and paste the following classes on it.
[Link] 21/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
package [Link];
Tutorials ([Link] Training ([Link] Consulting ([Link]
([Link] import static [Link];
import static [Link];
Company ([Link]
import Contact
static us ([Link]
[Link];
import static [Link]; GET MORE...
import static [Link];
import static [Link];
Read Premium Content ...
([Link]
import [Link];
import [Link];
Book Onsite or Virtual Training
import [Link]; ([Link]
import [Link];
Consulting
import [Link];
([Link]
import [Link];
import [Link];
import [Link];
TRAINING EVENTS
Now offering virtual, onsite and
/**
* Init data for unit test online training
*/ ([Link]
public class DataService {
final Movie theFellowshipOfTheRing = new Movie("the fellowship of the Ring", new Date(),
"178 min");
final Movie theTwoTowers = new Movie("the two Towers", new Date(), "179 min");
final Movie theReturnOfTheKing = new Movie("the Return of the King", new Date(), "201
min");
[Link] 22/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
ArrayList<TolkienCharacter>();
[Link](guruk);
Tutorials ([Link] Training ([Link] Consulting ([Link]
[Link](merry);
([Link] [Link](pippin);
return orcsWithHobbitPrisoners;
Company ([Link] Contact us ([Link]
}
GET MORE...
public TolkienCharacter getFellowshipCharacter(String name) { Read Premium Content ...
List<TolkienCharacter> list = getFellowship();
([Link]
return [Link]().filter(s-> [Link](name)).findFirst().get();
} Book Onsite or Virtual Training
public Map<Ring, TolkienCharacter> getRingBearers() { ([Link]
Consulting
Map<Ring, TolkienCharacter> ringBearers = new HashMap<>();
([Link]
// ring bearers
[Link]([Link], galadriel); TRAINING EVENTS
[Link]([Link], gandalf);
[Link]([Link], elrond); Now offering virtual, onsite and
[Link]([Link], frodo);
online training
return ringBearers;
} ([Link]
[Link] 23/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
package [Link];
Tutorials ([Link] Training ([Link] Consulting ([Link]
([Link] import static [Link];
import static [Link];
Company ([Link] Contact
import static us ([Link]
[Link];
GET MORE...
import [Link];
Read Premium Content ...
import [Link]; ([Link]
import [Link];
Book Onsite or Virtual Training
import [Link];
([Link]
import [Link];
Consulting
import [Link];
([Link]
class DataServiceTest {
TRAINING EVENTS
// TODO initialize before each test
DataService dataService; Now offering virtual, onsite and
@Test online training
void ensureThatInitializationOfTolkeinCharactorsWorks() { ([Link]
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
@Test
void ensureThatEqualsWorksForCharaters() {
Object jake = new TolkienCharacter("Jake", 43, HOBBIT);
Object sameJake = jake;
Object jakeClone = new TolkienCharacter("Jake", 12, HOBBIT);
// TODO check that:
// jake is equal to sameJake
// jake is not equal to jakeClone
fail("not yet implemented");
}
@Test
void checkInheritance() {
TolkienCharacter tolkienCharacter = [Link]().get(0);
// TODO check that [Link] is not a movie class
fail("not yet implemented");
}
@Test
void ensureFellowShipCharacterAccessByNameReturnsNullForUnknownCharacter() {
// TODO imlement a check that [Link] returns null for an
// unknow felllow, e.g. "Lars"
fail("not yet implemented");
}
@Test
void ensureFellowShipCharacterAccessByNameWorksGivenCorrectNameIsGiven() {
// TODO imlement a check that [Link] returns a fellow for
an
// existing felllow, e.g. "Frodo"
fail("not yet implemented");
}
@Test
void ensureThatFrodoAndGandalfArePartOfTheFellowsip() {
// TODO check that Frodo and Gandalf are part of the fellowship
fail("not yet implemented");
}
@Test
void ensureThatOneRingBearerIsPartOfTheFellowship() {
// TODO test that at least one ring bearer is part of the fellowship
fail("not yet implemented");
}
[Link] 24/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
@Tag("slow")
@DisplayName("Minimal
Tutorials ([Link] stress testing: run this test Consulting
Training ([Link] 1000 times to ")
([Link]
void ensureThatWeCanRetrieveFellowshipMultipleTimes() {
([Link] dataService = new DataService();
assertNotNull([Link]());
Company ([Link] Contact us should
([Link]
fail("this run 1000 times");
GET MORE...
}
Read Premium Content ...
@Test
void ensureOrdering() { ([Link]
List<TolkienCharacter> fellowship = [Link](); Book Onsite or Virtual Training
@Test
void ensureThatFellowsStayASmallGroup() {
// TODO Write a test to get the 20 element from the fellowship throws an
// IndexOutOfBoundsException
fail("not yet implemented");
}
Solve the TODO and ensure that all tests can be successfully executed from your IDE. You may find issues in
the DataService with these tests, fix them if you encounter them.
Solution
JAVA
public boolean update() {
try {
[Link](2000);
} catch (InterruptedException e) {
[Link]();
}
return true;
}
7.6. Develop a test to constrain the execution time of the long running
method
Create a new test method in your DataServiceTest . Use the assertTimeout assert statement to ensure
that this test does not run longer than 3 seconds.
Solution
[Link] 25/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
method for
Tutorials ([Link]
email verification
Training ([Link] Consulting ([Link]
([Link] 8.1. Create the data model used for testing
Company ([Link]
Create the Contact us ([Link]
[Link] package and copy and paste the following classes on it.
GET MORE...
package [Link]; Read Premium Content ...
JAVA
([Link]
/**
* Validates if the given input is a valid email address.
*
* @param emailPattern The {@link Pattern} used to validate the given email.
* @param email The email to validate.
* @return {@code true} if the input is a valid email. {@code false} otherwise.
*/
public static boolean isValidEmail(CharSequence email) {
return email != null && EMAIL_PATTERN.matcher(email).matches();
}
[Link] 26/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
package [Link];
Tutorials ([Link] Training ([Link] Consulting ([Link]
([Link] import static [Link];
import static [Link];
Company ([Link] Contact
import static us ([Link]
[Link];
GET MORE...
import [Link];
import [Link];
Read Premium Content ...
([Link]
class EmailValidatorTest {
Book Onsite or Virtual Training
// TODO Write test for EmailValidator ([Link]
// The names of the methods should give you a pointer what to test for
Consulting
@Test ([Link]
public void ensureThatEmailValidatorReturnsTrueForValidEmail() {
}
TRAINING EVENTS
assertTrue([Link]("[Link]@[Link]"));
@Test
@DisplayName("Ensure that a missiong top level domain returns false")
public void emailValidator_InvalidEmailNoTld_ReturnsFalse() {
fail("Fixme");
}
@Test
public void emailValidator_InvalidEmailDoubleDot_ReturnsFalse() {
fail("Fixme");
}
@Test
public void emailValidator_InvalidEmailNoUsername_ReturnsFalse() {
fail("Fixme");
}
@Test
public void emailValidator_EmptyString_ReturnsFalse() {
fail("Fixme");
}
@Test
public void emailValidator_NullEmail_ReturnsFalse() {
fail("Fixme");
}
Fix all the failing test, unfortunately the test specification is not very good. Try to write reasonable tests which
fit the method name.
8.3. Verify
Run your new test via the IDE. Verify that your code compiles and your test are running via the command line.
8.4. Solution
The following listing contains a possible implementation of the test.
Solution
[Link] 27/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
package [Link];
Tutorials ([Link] Training ([Link] Consulting ([Link]
([Link]
import static [Link];
Company ([Link] Contact
import static us ([Link]
[Link];
import static [Link]; GET MORE...
import static [Link];
Read Premium Content ...
import [Link]; ([Link]
import [Link];
Book Onsite or Virtual Training
import [Link];
([Link]
import [Link];
Consulting
([Link]
public class DataModelAssertThrowsTest {
TRAINING EVENTS
@Test
Now offering
@DisplayName("Ensure that access to the fellowship throws exception outside virtual, onsite and
the valid
range")
void exceptionTesting() { online training
DataService dataService = new DataService(); ([Link]
Throwable exception = assertThrows([Link], () ->
[Link]().get(20));
assertEquals("Index 20 out of bounds for length 9", [Link]());
}
@Test
@Disabled("Please fix and enable")
public void ensureThatAgeMustBeLargerThanZeroViaSetter() {
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
// use assertThrows() rule to check that the message is:
// Age is not allowed to be smaller than zero
[Link](-1);
@Test
@Disabled("Please fix and enable")
public void testThatAgeMustBeLargerThanZeroViaConstructor() {
// use assertThrows() rule to check that an IllegalArgumentException exception is
thrown and
// that the message is:
// "Age is not allowed to be smaller than zero"
Fix the disabled tests and enable them. The name should give a good indication what you have to do test here.
You may discover that the data model does not behave a expected by the test, fix them in this case.
9.2. Verify
Run your update test via the IDE. Verify that your code compiles and your test are running via the command
line with the mvn clean verify .
9.3. Solution
Solution
[Link] 28/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
package [Link];
Tutorials ([Link] Training ([Link] Consulting ([Link]
([Link] import static [Link];
TRAINING EVENTS
10. Exercise: Writing nested tests to group testsNow
foroffering
display virtual, onsite and
10.1. Write tests online training
([Link]
Create the following test.
JAVA
package [Link];
import static [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
class UsingNestedTests {
@BeforeEach
void setup() {
list = [Link]("JUnit 5", "Mockito");
}
@Test
void listTests() {
assertEquals(2, [Link]());
}
@Test
void checkSecondElement() {
assertEquals(("Mockito"), [Link](1));
}
10.2. Solution
The following listing contains a possible implementation of the test.
Solution
[Link] 29/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
class ConverterUtilTest {
@TestFactory
Stream<DynamicTest> ensureThatCelsiumConvertsToFahrenheit() {
return [Link](celsiusFahrenheitMapping).map(entry -> {
// access celcius and fahrenheit from entry
int celsius = entry[0];
int fahrenheit = entry[1];
return null;
// return a dynamicTest which checks that that the convertion from celcius to
// fahrenheit is correct
});
Stream<DynamicTest> ensureThatFahrenheitToCelsiumConverts() {
return null;
// TODO Write a similar test fahrenheit to celsius
}
}
Fix all the failing test, unfortunately the test specification is not very good. Try to write reasonable tests which
fit the method name.
Show Solution
11.3. Verify
Run your new test via the IDE and ensure that you have 6 tests running succesfull.y
Verify that your code compiles and your test are running via the command line either with ./gradlew
test`or with the `mvn clean verify depending on your build system.
[Link] 30/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
package [Link];
import static [Link];
import [Link];
import [Link];
class ParameterizedExampleTest {
// class to be tested
class MyClass {
public int multiply(int i, int j) {
return i * j;
}
}
}
Create a new test method in ConverterUtilTest which also uses a parameterized test.
12.3. Verify
Run your new test via the IDE.
convertertestresult10
We're sorry, the image above is broken, please let us know.
Verify that your code compiles and your test are running via the command line with the ./gradlew test or
mvn clean verify command based on your build system.
[Link] 31/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
@ParameterizedTest
Tutorials ([Link] Training ([Link]
@ValueSource(strings Consulting
= { "WINDOW", "Microsoft Windows [Version ([Link]
10.?]" })
([Link] void ensureWindowsStringContainWindow(String name) {
assertTrue([Link]().contains("window"));
Company ([Link]
} Contact us ([Link]
GET MORE...
@DisplayName("A negative value for year is not supported by the leap year computation.")
@ParameterizedTest(name = "For example, year {0} is not supported.")
Read Premium Content ...
@ValueSource(ints = { -1, -4 }) ([Link]
void ensureYear(int year) {
assertTrue(year < 0);
Book Onsite or Virtual Training
} ([Link]
Consulting
@ParameterizedTest(name = "{0} * {1} = {2}")
@CsvSource({ "0, 1, 0", "1, 2, 2", "49, 50, 2450", "1, ([Link]
100, 100" })
void add(int first, int second, int expectedResult) {
MyClass calculator = new MyClass();
TRAINING EVENTS
assertEquals(expectedResult, [Link](first, second),
Now offering virtual,
() -> first + " * " + second + " should equal " + expectedResult); onsite and
}
online training
([Link]
13. Exercise: Using the @TempDir annotation to create
temporary files and paths
In this exercise you learn how to use the @TempDir annotation to let JUnit 5 create files and paths on request
in your test and to automatically remove them after the test.
JAVA
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Ensure that the Path given to you by the @TempDir annotation if writable
Ensure that a appending to a file with [Link] which has not yet been created with
[Link] throws an exception
Ensure that you can write to the file once you created it
HINT:
[Link] 32/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
JAVA
@Test
Tutorials ([Link] Training ([Link]
void ensureThatPathFromTempDirISWritable(@TempDir Consulting
Path path) { ([Link]
Gradle:
GRADLE
implementation '[Link]:[Link]'
JAVA
package [Link];
import [Link];
@Inject
String s;
@Inject
public Service() {
}
@Inject
public Service(String s) {
this.s = s;
}
}
Write a test that validates that the Service class only has one constructor annotated with @Inject .
HINT:
14.3. Solution
Solution
[Link] 33/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
Gradle creates these automatically, if you run the ./gradlew build command and with Maven you run the
Tutorials ([Link] Training
mvn clean verify command. Consulting ([Link]
([Link]
surefire-report:report
([Link]
Run this for your project and check the build folder for the generated test reports.
Company ([Link] Contact us ([Link]
GET MORE...
16. Exercise: Clone the JUnit5 Github repo and review tests
Read Premium Content ...
([Link]
Open JUnit5 Github page ([Link] in your browser and clone the repo.
Book Onsite or Virtual Training
Import the project into your favorite IDE and review some of the tests, e.g. the platform-tests contains a
([Link]
lot of useful tests. Consulting
([Link]
17. Overview of JUnit5 annotations
TRAINING EVENTS
The following table gives an overview of the most important annotations in JUnit 5 from the
[Link] package. Now offering virtual, onsite and
online training
Table 2. Annotations ([Link]
Annotation Description
@BeforeEach Executed before each test. Used to prepare the test environment, e.g.,
initialize the fields in the test class, configure the environment, etc.
@AfterEach Executed after each test. Used to cleanup the test environment, e.g., delete
temporary data, restore defaults, cleanup expensive memory structures.
@DisplayName(" <Name> that will be displayed by the test runner. In contrast to method
<Name>") names the name can contain spaces to improve readability.
@BeforeAll Annotates a static method which is executed once, before the start of all
tests. It is used to perform time intensive activities, for example, to connect
to a database. Methods marked with this annotation need to be defined as
static to work with JUnit.
@AfterAll Annotates a static method which is executed once, after all tests have been
finished. It is used to perform clean-up activities, for example, to disconnect
from a database. Methods annotated with this annotation need to be
defined as static to work with JUnit.
@Nested Lets you nest inner test classes to group your tests and to have additional
@BeforeEach and @AfterEach methods.
@Tag("<TagName>") Tags a test method, tests in JUnit 5 can be filtered by tag. E.g., run only
tests tagged with "fast".
@ExtendWith Lets you register an Extension class that adds functionality to the tests
18. Conclusion
JUnit 5 makes is easy to write software tests.
The implementation of all these examples and code snippets can be found over on Github
([Link] The Maven examples are located in JUnit with Maven
([Link] and the Gradle examples are located in JUnit
5 with Gradle ([Link]
If you need more assistance we offer Online Training ([Link] and Onsite training
([Link] as well as consulting ([Link]
[Link] 34/35
28/02/2023 08:44 JUnit 5 tutorial - Learn how to write unit tests
Company ([Link]
19. JUnit Resources
Contact us ([Link]
GET MORE...
JUnit Homepage ([Link] Read Premium Content ...
([Link]
JUnit 5 user guide ([Link]
Book Onsite or Virtual Training
([Link]
Last updated 15:08 17. Aug 2021
Consulting
Legal ([Link] Privacy Policy ([Link] Change consent
([Link]
TRAINING EVENTS
Now offering virtual, onsite and
online training
([Link]
[Link] 35/35
When writing unit tests for model classes, key considerations include accurately reflecting the class's behavior, covering all logical paths, ensuring test data completeness, and verifying interactions between model components. Tests should also validate data integrity, such as checking that equals and hashCode methods function correctly. Handling edge cases, like invalid inputs and boundary values, is equally essential to ensure robustness .
The DataService class manages a collection of Tolkien characters by initializing lists of characters and providing methods to retrieve them. Although this centralized data initialization supports reuse in tests, challenges arise in ensuring data integrity and handling test-specific modifications without affecting the global state. This requires care in designing tests to avoid unintended interactions and ensure the consistency of character data across tests .
The use of assertAll in JUnit tests is significant because it allows multiple assertions to be grouped and executed together. This means that even if one assertion fails, the remainder will still be evaluated, providing a comprehensive overview of multiple test outcomes in a single execution. This approach enhances test coverage and debugging efficiency by allowing multiple conditions to be checked at once .
Tests can be simplified using the @BeforeEach annotation, which allows test setup code to be executed before each test method, helping to avoid code duplication. This consolidation promotes cleaner test code and eases the maintenance of test setups across multiple test methods .
To configure a Maven project to use JUnit 5, it is necessary to set the Maven compiler source and target to version 11, and configure the maven-surefire-plugin and maven-failsafe-plugin to version 2.22.2. Additionally, dependencies for junit-jupiter-api and junit-jupiter-engine with version 5.7.2 should be added with the test scope to the pom file .
To fix a bug in a JUnit test, first identify the issue, such as the multiply function performing division instead of multiplication. After fixing the code, re-run the tests to verify the solution by observing a green bar in the JUnit view; this indicates successful test execution. This process involves critical evaluation to ensure the function now meets the requirements and expected behavior .
A JUnit test can ensure the ordering of elements by asserting the expected sequence with assert statements, checking each element's position within a collection. By validating the order of elements, tests confirm that operations preserving order, like sorting or insertion, are correctly implemented. This is critical when operations assume a specific element sequence, impacting algorithmic correctness and output predictability .
Setting up a JUnit test project in Gradle requires updating the build.gradle file with appropriate dependencies and configurations, such as using testImplementation for JUnit 5 and specifying to useJUnitPlatform. In Maven, it involves modifying the pom.xml file to include surefire and failsafe plugins and JUnit dependencies. While both achieve similar testing goals, Gradle provides more flexibility in scripting and dependency management versus Maven's simpler, declarative approach .
JUnit primarily provides unit testing capabilities, focusing on test organization, execution, and validation. It is integrated with build tools like Maven and Gradle to facilitate automated testing. Conversely, Gradle is a versatile build automation tool that, among other functionalities, supports JUnit tests. Gradle allows configuration of dependencies and compile tasks, making it a comprehensive system for handling the build lifecycle, including testing .
Constraining the execution time of a method in unit tests is important to ensure that the code executes efficiently within acceptable performance limits. This is crucial in scenarios involving long-running operations, where excessive execution time can indicate potential inefficiencies or problematic code paths. Asserting timeout limits, therefore, ensures that the code meets performance expectations and helps identify bottlenecks .