1 JUnit 5 Introduction-Merged

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 174

JUnit 5 Introduction

This lesson introduces JUnit 5, one of the most popular and powerful testing framework for Java.

WE'LL COVER THE FOLLOWING

• Introduction
• What is Junit 5?
• Course Interactivity

Introduction #
Junit was developed by Kent Beck and Erich Gamma. Its first version was
released in 1997. It became one of the most popular testing frameworks in the
Java community due to its ease of use. It is a lightweight testing framework
which allowed Java developers to write unit test cases in Java language. The
recent version released is 5.3.2, which is termed as Junit 5.

What is Junit 5? #
Junit 5 is a powerful and popular Java testing framework. It is composed of
many different modules. These different modules are parts of three sub-
projects as follows:-

Junit Platform
Junit Jupiter
Junit Vintage

In short it is represented as,

JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage

The above three projects are core to Junit 5. The architecture of JUnit 5 mostly
comprises of these 3 components/sub-projects. In the next few lessons, we will
take a look at more details of above three sub-projects.

Course Interactivity #
Interactive practice environments are embedded in every lesson to give you a
hands-on learning experience.

Let’s look into an interactive demo below. you don’t need to understand this
for now but here’s how we are going to learn using Educative. Just run below
JUnit 5 code widget and have a look at output without any setup or download.
You can also edit code and run to understand more.

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

class HelloWorldTest {
@Test
void checkHelloMsg() {
assertEquals("Hello World", "Hello World");
}
}

JUnit 5 - Introduction to JUnit


‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬
Introduction to JUnit
Junit 5 Architecture

This lesson describes Junit 5 architecture, along with their core functionality.

Junit 5 Architecture has three main components -

**Junit Platform**
It provides a core foundation to help launching testing frameworks on
JVM. It acts as an interface between JUnit and its clients such as build
tools (`Maven and Gradle`) and IDE's (`Eclipse and IntelliJ`). It
introduces the concept of a `Launcher` which external tools use to
discover, filter, and execute tests.

It also provides the TestEngine API for developing a testing framework that
runs on the JUnit platform. Using TestEngine API , 3rd party testing libraries
such as Spock, Cucumber, and FitNesse can directly plug in and provide their
custom TestEngine.

**Junit Jupiter**
It provides a new programming model and extension model for writing
tests and extensions in Junit 5. It has a whole new annotation to write test
cases in Junit 5. Some of the annotations are `@BeforeEach`,
`@AfterEach`, `@AfterAll`, `@BeforeAll` etc. It implements TestEngine
API provided by Junit Platform so that Junit 5 test can be run.

**Junit Vintage**
The term `Vintage` basically means **classic**. Thus, this sub-project
provides extensive support for writing test cases in JUnit 4 and JUnit 3.
Thus, backward compatibility is been provided by this project.

JUnit 5 Architecture

Quiz on JUnit 5 Architecture

Q
JUnit 4 test cases are run on JUnit Vintage Engine.
COMPLETED 0%
1 of 1

Quiz on JUnit 5 Architecture

Q
JUnit 5 test cases are run on JUnit Jupiter Engine.

COMPLETED 0%
1 of 1

In the next lesson, we will learn to create our first JUnit 5 test case.
Building Your First Junit 5 Test

This lesson provides step by step hands-on approach to run JUnit 5 test case on Eclipse IDE.

Project Setup
Please install the following softwares on your machine.
Java 8
JUnit 5 tests will run with Java 8 or above. Please download and install the
latest update of Java 8 or above from the official Oracle web site.
www.oracle.com/technetwork/java/javase/downloads/index.html .

After installing Java, you can check your Java version by running the
following command -

Eclipse Oxygen or above


You can download the latest version from Eclipse web site -
https://www.eclipse.org/downloads/packages/release/neon/3/eclipse-ide-java-
ee-developers .

Steps to write your rst Junit 5 test case in Eclipse


Step 1 - Launch Eclipse IDE.

Step 2 - Create a new Java Project. Right click on File --> New --> Java Project
as demonstrated in the figure below.
A new popup window by name “New Java Project” will be opened as shown in
the figure below.

Step 3 - Provide a Project name: say, Junit5

Step 4 - Select JRE as 1.8 and above.

Step 5 - Click Finish.

A new Java Project will be created by name - Junit5


It’s a best practice to create JUnit test cases in the test folder.

Step 6 - Expand the Junit5 Java project. Right-click on project root. Traverse to
Build Path --> New Source Folder... as shown in the figure below.
Step 7 - A "New Source Folder" popup will be opened as shown in the figure
below.

Step 8 - Provide folder name as "test" and click Finish.


Step 9 - Right-click on test folder and traverse to New --> Junit Test Case as
demonstrated in the figure below.
Step 10 - A "New Junit Test Case" popup will be opened as shown in the figure
below.

In order to create a new JUnit 5 test case, perform the following steps:-

Step 11 - Select "New Junit Jupiter test". This will create Junit 5 test case.

Step 12 - Provide any package name of your choice.

Step 13 - Provide class name as, FirstJunit5Test.

Step 14 - Click Finish.


Step 15 - Add JUnit 5 library to the build path. Click Ok as shown in the figure
below.
A new test class by name FirstJunit5Test will be created. It will have
following snippet of code as shown below.

FirstJunit5Test.java

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class FirstJunit5Test {

@Test
void test() {
fail("Not yet implemented");
}

It has a method “test()”. This method has an annotation as, @Test. It signifies
that this is a test method in to which we write our code to test.

Step 16 - Right-click on editor window and run as Junit test case, as shown in
the figure below.

The test case fails as shown in fig below. It gives “AssertionFailedError: Not yet
implemented”. It is because in test() method it is written ‘fail(“Not yet
implemented”)’ assertion. This assertion fails the test case as it is not yet
implemented. More on @Test and fail() in upcoming lessons.

Building Your First JUnit 5 Test


‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬

Building Your First JUnit 5 Test

In the next lesson, we will look into @Test annotation in JUnit 5.


@Test Annotation

In this lesson, we’ll look into a quick review of JUnit’s 5 @Test annotation. This annotation provides a powerful tool
for performing unit testing.

WE'LL COVER THE FOLLOWING

• Class Under Test


• Method Under Test
• Testing the Method
• Explanation
• Running Junit 5 Test

Class Under Test #


Let’s first create a class with some functionality to test. This class will have the
method for which we will write our test scenarios to demonstrate the @Test
annotation’s usability. The class name in our example would be - OddEven , as
shown in the code below.

Method Under Test #


Inside OddEven class, let’s create a method by name isEvenNumber() . This
method will take in an integer value and return a boolean value that whether
the given number is even number or not. If the number is even it will return
true and if it is odd then it will return false. Let’s have a look into the code
below.

OddEven.java

package com.hubberspot.junit5;

public class OddEven {

public boolean isNumberEven(int number) {


return number % 2 == 0;
}

Testing the Method #


In order to test isEvenNumber() method, we will write use cases that it suppose
to fulfill. The test scenarios would be:-

1. Given an even number, when isEvenNumber() method is called, then it


should return true.

2. Given an odd number, when isEvenNumber() method is called, then it


should return false.

In order to test isEvenNumber() method, we will write a test class which will
have two methods to test the above two scenarios. The test class will be
created in the test folder as discussed in the previous lesson.

In order for the methods created in the test class to be recognized as test
methods, we mark it with @Test annotation. Let’s have a look at the test class
and test methods:-

OddEvenTest.java

OddEven.java

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class OddEvenTest {

@Test
void givenEvenNumber_whenIsEvenIsCalled_thenTrueIsReturned() {
OddEven oddEven = new OddEven();
assertTrue(oddEven.isNumberEven(10));
}

@Test
void givenOddNumber_whenIsEvenIsCalled_thenFalseIsReturned() {
OddEven oddEven = new OddEven();
assertFalse(oddEven.isNumberEven(11));
}

}
You can perform code changes to above code widget, run and practice
different outcomes.

Explanation #
Junit 5 @Test annotation has following characteristics:-

1. It is applied over methods to mark them as test methods.

2. It is present in org.junit.jupiter.api package.

3. Its visibility can be made public, default and protected.

assertTrue() methods take in a boolean value and ensure that value is true. If
a false value is passed, it will fail the test case.

assertFalse() methods take in a boolean value and ensure that value is false.
If a true value is passed, it will fail the test case.

We will discuss more about assertTrue() and assertFalse() methods in


upcoming lessons.

Running Junit 5 Test #


As shown in the figure below, upon running the two test methods, it gives
success that both the test cases are passed.
JUnit 5 - @Test Annotation
‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬

@Test annotation

In the next chapter, we will look into various Assertions JUnit 5 supports.
What is the Assertion in JUnit 5?

This lesson describes Assertions in JUnit 5.

WE'LL COVER THE FOLLOWING

• Assertions in JUnit 5
• Assert methods in Assertions API

Assertions in JUnit 5 #
JUnit 5 assertions help us in validating the expected output with the actual
output of a test case. In short, assertions are nothing but static methods that
we call in our tests to verify expected behavior. All JUnit Jupiter assertions are
present in the org.junit.jupiter.Assertions class.

These methods support Java 8 lambda expressions and are extensively


overloaded to support different types such as primitives, objects, streams,
arrays etc.

JUnit 5 - Assertions
‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬
JUnit 5 Assertions

Assert methods in Assertions API #

Assert Method What It Does

assertNull() Asserts that actual is null.

assertNotNull() Asserts that actual is not null.

fail() Simply fails the test

Assert that expected and actual


assertSame()
refer to the same object.

Assert that expected and actual


assertNotSame()
do not refer to the same object.

assertTrue() asserts that actual is true.

assertFalse() asserts that actual is false.

Assert that expected and actual


assertEquals()
are equal.

Assert that expected and actual


assertNotEquals()
are not equal.

Assert that expected and actual


assertArrayEquals()
arrays are equal.

Asserts that expected and actual


assertIterableEquals()
iterables are deeply equal

Assert if an executable throws the


assertThrows()
specified exception type.

assertAll() Assert multiple assertions in


groups.

Assert that the execution of a


assertTimeout() supplied Executable ends before a
given timeout

Assert that the execution of the


Executable will be preemptively
assertTimeoutPreemptively()
aborted if the timeout is
exceeded.

In our previous lessons we have used few assertions such as, fail(),
assertTrue(), assertFalse() and assertEquals() etc. In our upcoming lesson, we
will discuss each and every Assertion in more detail.
assertNull() method

This lesson demonstrates how to use assertNull() method in JUnit 5 to assert test conditions.

WE'LL COVER THE FOLLOWING

• assertNull() method
• Demo
• Class Under Test - StringUtils
• Output
• Explanation -

assertNull() method #
Assertions API provide static assertNull() method. This method helps us in
validating that the particular object is null. This method takes an actual value
and checks whether it is null or not.

If the actual value is null then test case will pass.


If the actual value is not null then test case will fail.

There are basically three overloaded methods for assertNull which are
described below:-

public static void assertNull(Object actual)

public static void assertNull(Object actual, String message)

public static void assertNull(Object actual, Supplier<String> messageSupplier)

1. assertNull(Object actual) - It asserts whether actual value is null or not.

2. assertNull(Object actual, String message) - It asserts whether actual


value is null or not. In case, if the actual value is not null then the test
case will fail with a provided message.

3. assertNull(Object actual, Supplier<String> messageSupplier) - It assert


whether actual value is null or not. In case, if the actual value is not null
then the test case will fail with a provided message through Supplier
function. The main advantage of using Supplier function is that it lazily
evaluates to String only when the test case fails.

JUnit 5 Assertions - assertNull method


‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬

assertNull method

Demo #
Step 1 - Create a Java class in Eclipse as discussed in previous lessons.

Step 2 - Give it a name as, StringUtils.

StringUtils.java

package com.hubberspot.junit5.assertions;

public class StringUtils {

public static String reverse(String input) {


if(input == null) {
return null;
}
if(input.length() == 0) {
return "";

char[] charArray = input.toCharArray();


int start = 0;
int end = input.length() - 1;

while(start < end) {


char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
start++;
end--;
}

return new String(charArray);


}

Class Under Test - StringUtils #


StringUtils is our class under test. It has one method as, reverse() . This
method takes in a String and returns reverse of it.

For example -

1. If we provide input String as, “ABCD”, it returns back “DCBA”.

2. If we provide input String as, “Student”, it returns back “tnedutS”.

3. If we provide input String as, null, it returns back null.

4. If we provide input String as, “”, it returns back “” String.

Step 3 - Create a test class by name, "StringUtilsTest" . This test class will
demonstrate all overloaded assertNull() methods.

StringUtilsTest.java

StringUtils.java

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.*;


import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
class StringUtilsTest {

// ******** assertNull Example - Start **********


@Test
void givenNullString_whenReverseIsCalled_thenNullIsReturned() {
String actual = StringUtils.reverse((null));

// assertNull without message


assertNull(actual);
}

@Test
void givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() {
String actual = StringUtils.reverse((""));
String message = "Actual String should be null !!! ";

// assertNull with message


assertNull(actual, message);
}

@Test
void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned() {
String actual = StringUtils.reverse(("ABCD"));
Supplier<String> messageSupplier = () -> "Actual String should be null !!! "

// assertNull with Java 8 MessageSupplier


assertNull(actual, messageSupplier);
}

// ******** assertNull Example - End **********


}

You can perform code changes to above code widget, run and practice
different outcomes.

Step 4 - Run StringUtilsTest class as Junit Test.

Output #
Explanation - #
The order of execution of test cases depends on Junit 5. In StringUtilsTest class
there are 3 @Test methods:-

1. givenNullString_whenReverseIsCalled_thenNullIsReturned() - It tests the


scenario that when null is provided to reverse() method of StringUtils
class, then null is returned. So, on line 15 providing assertNull() asserts
that actual value returned is null. Thus, it passes the Junit test case.

2. givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() - It
tests the scenario that when “” is provided to reverse() method of
StringUtils class, then “” is returned. Here, return value is empty string
which is not null. So, on line 24 providing assertNull() asserts that
actual value returned is null. Thus, it fails the Junit test case because
actual value returned is “”. In this test case, we are using overloaded
assertNull() method, which takes String message as second argument.
As, this test case doesn’t satisfy assertion condition, it fails and give
" AssertionFailedError: Actual String should be null !!! ==> expected: but
was: <>". It gives AssertionFailedError followed by String message we
provide to assertNull() method.

3. givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned - It
tests the scenario that when ABCD is provided to reverse() method of
StringUtils class, then DCBA is returned. Here, return value is not null.
So, on line 33 providing assertNull() asserts that actual value returned
is null. Thus, it fails the Junit test case because actual value returned is
DCBA. In this test case, we are using overloaded assertNull() method,
which takes Supplier<String> messageSupplier as second argument. As,
this test case doesn’t satisfy assertion condition, it fails and give
" AssertionFailedError: Actual String should be null !!! ==> expected: but
was: <DCBA>". It gives AssertionFailedError followed by lazily evaluates
String message we provide to assertNull() method, as lambda
expression.

In the next lesson, we will look into assertNotNull() assertion.


assertNotNull() method

This lesson demonstrates how to use assertNotNull() method in JUnit 5 to assert test conditions.

WE'LL COVER THE FOLLOWING

• assertNotNull() method
• Demo
• Class Under Test - StringUtils
• Output
• Explanation -

assertNotNull() method #
Assertions API provide static assertNotNull() method. This method helps us
in validating that particular object is not null. This method takes the actual
value and checks whether it is null or not.

If the actual value is not null then test case will pass.
If the actual value is null then test case will fail.

There are basically three overloaded methods for assertNotNull:-

public static void assertNotNull(Object actual)

public static void assertNotNull(Object actual, String message)

public static void assertNotNull(Object actual, Supplier<String> messageSupplier)

1. assertNotNull(Object actual) - It assert whether actual value is not null.

2. assertNotNull(Object actual, String message) - It assert whether actual


value is not null. In case, if the actual value is null then test case will fail
with the provided message.
3. assertNotNull(Object actual, Supplier<String> messageSupplier) - It
assert whether actual value is not null. In case, if the actual value is null
then test case will fail with the provided message through Supplier
function. The main advantage of using Supplier function is that it lazily
evaluates to String only when the test case fails.

Demo #
In our previous lesson, we created a class by name, StringUtils. It has the
reverse() method, which reverses the String passed to it.

JUnit 5 Assertions - assertNotNull method


‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬

assertNotNull method

StringUtils.java

package com.hubberspot.junit5.assertions;

public class StringUtils {

public static String reverse(String input) {


if(input == null) {
return null;
}
if(input.length() == 0) {
return "";
}

char[] charArray = input.toCharArray();


int start = 0;
int end = input.length() - 1;

while(start < end) {


char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
start++;
end--;
}

return new String(charArray);


}

Class Under Test - StringUtils #


StringUtils is our class under test. It has one method as, reverse() . This
method takes in a String and returns reverse of it.

For example -

1. If we provide input String as, “ABCD”, it returns back “DCBA”.

2. If we provide input String as, “Student”, it returns back “tnedutS”.

3. If we provide input String as, null, it returns back null.

4. If we provide input String as, “”, it returns back “” String.

In our previous lesson, we created a test class by name, “ StringUtilsTest ”.


This test class will demonstrate all overloaded assertNotNull() methods.

StringUtilsTest2.java

package com.hubberspot.junit5.assertions;

import static org.junit.jupiter.api.Assertions.*;

import java.util.function.Supplier;
import org.junit.jupiter.api.Test;

class StringUtilsTest2 {

// ******** assertNotNull Example - Start **********


@Test
void givenNullString_whenReverseIsCalled_thenNullIsReturned() {
String actual = StringUtils.reverse((null));
String message = "Actual String should not be null !!! ";

// assertNotNull with message


assertNotNull(actual, message);
}

@Test
void givenNullString_whenReverseIsCalled_thenNullIsReturned2() {
String actual = StringUtils.reverse((null));
Supplier<String> messageSupplier = () -> "Actual String should not be null !!

// assertNotNull with Java 8 MessageSupplier


assertNotNull(actual, messageSupplier);
}

@Test
void givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() {
String actual = StringUtils.reverse((""));

// assertNotNull without message


assertNotNull(actual);
}

@Test
void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned() {
String actual = StringUtils.reverse(("ABCD"));

// assertNotNull without message


assertNotNull(actual);
}

// ******** assertNotNull Example - End **********


}

StringUtilsTest2.java

StringUtils.java

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.*;

import java.util.function.Supplier;
import org.junit.jupiter.api.Test;

class StringUtilsTest2 {

// ******** assertNotNull Example - Start **********


@Test
void givenNullString_whenReverseIsCalled_thenNullIsReturned() {
String actual = StringUtils.reverse((null));
String message = "Actual String should not be null !!! ";

// assertNotNull with message


assertNotNull(actual, message);
}
@Test
void givenNullString_whenReverseIsCalled_thenNullIsReturned2() {

String actual = StringUtils.reverse((null));


Supplier<String> messageSupplier = () -> "Actual String should not be null !

// assertNotNull with Java 8 MessageSupplier


assertNotNull(actual, messageSupplier);
}

@Test
void givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() {
String actual = StringUtils.reverse((""));

// assertNotNull without message


assertNotNull(actual);
}

@Test
void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned() {
String actual = StringUtils.reverse(("ABCD"));

// assertNotNull without message


assertNotNull(actual);
}

// ******** assertNotNull Example - End **********


}

You can perform code changes to above code widget, run and practice
different outcomes.

Run StringUtilsTest class as JUnit Test.

Output #

Explanation - #
The order of execution of test cases depends on Junit 5. In StringUtilsTest2
class there are 4 @Test methods:-

1. givenNullString_whenReverseIsCalled_thenNullIsReturned() - It tests the


scenario that when null is provided to reverse() method of StringUtils
class, then null is returned. So, on line 17 providing assertNotNull()
asserts that actual value returned is not null. Thus, it fails the Junit test
case because actual value returned is null. In this test case, we are using
overloaded assertNotNull() method, which takes String message as
second argument. As, this test case doesn’t satisfy assertion condition, it
fails and give " AssertionFailedError: Actual String should not be null !!!
==> expected: not ". It gives AssertionFailedError followed by String
message we provide to assertNotNull() method.

2. givenNullString_whenReverseIsCalled_thenNullIsReturned2() - It tests the


scenario that when null is provided to reverse() method of StringUtils
class, then null is returned. So, on line 26 providing assertNotNull()
asserts that actual value returned is not null. Thus, it fails the Junit test
case because actual value returned is null. In this test case, we are using
overloaded assertNotNull() method, which takes Supplier<String>
messageSupplier as second argument. As, this test case doesn’t satisfy
assertion condition, it fails and give " AssertionFailedError: Actual String
should not be null !!! ==> expected: not ". It gives AssertionFailedError
followed by lazily evaluates String message we provide to
assertNotNull() method, as lambda expression.

3. givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() - It
tests the scenario that when “” is provided to reverse() method of
StringUtils class, then “” is returned. Here, return value is empty string
which is not null. So, on line 34 providing assertNotNull() asserts that
actual value returned is not null. Thus, it pass the Junit test case because
actual value returned is “” which is not null.

4. givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned - It
tests the scenario that when ABCD is provided to reverse() method of
StringUtils class, then DCBA is returned. Here, return value is not null.
So, on line 42 providing assertNotNull() asserts that actual value
returned is not null. Thus, it pass the Junit test case because actual value
returned is “DCBA” which is not null.
In our upcoming lesson, we will look how we can pass all above test cases
using assertNull() and assertNotNull() methods together.
Using assertNull() and assertNotNull() methods
together

This lesson demonstrates how to use assertNull() and assertNotNull() methods together in JUnit 5 to assert test
conditions.

WE'LL COVER THE FOLLOWING

• Demo
• Class Under Test - StringUtils
• Output
• Explanation -

Demo #
Step 1 - Create a Java class in Eclipse as discussed in previous lessons.

Step 2 - Give it a name as, StringUtils.`

StringUtils.java

package com.hubberspot.junit5.assertions;

public class StringUtils {

public static String reverse(String input) {


if(input == null) {
return null;
}

if(input.length() == 0) {
return "";
}

char[] charArray = input.toCharArray();


int start = 0;
int end = input.length() - 1;

while(start < end) {


char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
start++;
end--;

return new String(charArray);


}

Class Under Test - StringUtils #


StringUtils is our class under test. It has one method as, reverse() . This
method takes in a String and returns reverse of it.

For example -

1. If we provide input String as, “ABCD”, it returns back “DCBA”.

2. If we provide input String as, “Student”, it returns back “tnedutS”.

3. If we provide input String as, null, it returns back null.

4. If we provide input String as, “”, it returns back “” String.

Step 3 - Create a test class by name, “ StringUtilsTest ”. This test class will
demonstrate how to use assertNull() and assertNotNull() methods together
to pass previous lessons failed test cases.

StringUtilsTest.java

StringUtils.java

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.*;


import org.junit.jupiter.api.Test;

class StringUtilsTest {

@Test
void givenNullString_whenReverseIsCalled_thenNullIsReturned() {
String actual = StringUtils.reverse((null));
assertNull(actual);
}

@Test
void givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() {
String actual = StringUtils.reverse((""));
assertNotNull(actual);
}

@Test

void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned() {
String actual = StringUtils.reverse(("ABCD"));
assertNotNull(actual);
}

You can perform code changes to above code widget, run and practice
different outcomes.

Step 4 - Run StringUtilsTest class as Junit Test.

Output #

Explanation - #
The order of execution of test cases depends on Junit 5. In StringUtilsTest class
there are 3 @Test methods:-

1. givenNullString_whenReverseIsCalled_thenNullIsReturned() - It tests the


scenario that when null is provided to reverse() method of StringUtils
class, then null is returned. So, on line 11 providing assertNull() asserts
that actual value returned is null. Thus, it passes the Junit test case
because actual value returned is null.

2. givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() - It
tests the scenario that when “” is provided to reverse() method of
StringUtils class, then “” is returned. Here, return value is empty string
which is not null. So, on line 17 providing assertNotNull() asserts that

actual value returned is not null. Thus, it passes the Junit test case
because actual value returned is not null.

3. givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned - It
tests the scenario that when ABCD is provided to reverse() method of
StringUtils class, then DCBA is returned. Here, return value is not null.
So, on line 23 providing assertNotNull() asserts that actual value
returned is not null. Thus, it passes the Junit test case because actual
value returned is not null.

In the next lesson, we will look into assertEquals() assertion.


assertEquals() method

This lesson demonstrates how to use assertEquals() method in JUnit 5 to assert test conditions.

WE'LL COVER THE FOLLOWING

• assertEquals() method
• Demo
• Class Under Test - StringUtils
• Output
• Explanation -

assertEquals() method #
Assertions API provide static assertEquals() method. This method helps us in
validating that actual and expected values are equal. This method uses
equals() to assert the equality of actual and expected value.

If the actual value is equal to expected value then the test case will pass.
If the actual value is not equal to expected value then the test case will
fail.

There are basically three useful overloaded methods for assertEquals:-

public static void assertEquals(Object expected, Object actual)

public static void assertEquals(Object expected, Object actual, String message)

public static void assertEquals(Object expected, Object actual, Supplier<String> messageSuppl

1. assertEquals(Object expected, Object actual) - It asserts whether


expected and actual value are equal.

2. assertEquals(Object expected, Object actual, String message) - It


asserts whether expected and actual value are equal. In case, if the

expected value is not equal to actual value then test case will fail with a
provided message.

3. assertEquals(Object expected, Object actual, Supplier<String>


messageSupplier) - It assert whether expected and actual value are equal.
In case, if the expected value is not equal to actual value then test case
will fail with the provided message through Supplier function. The main
advantage of using Supplier function is that it lazily evaluates to String
only when the test case fails.

assertEquals method

Demo #
Step 1 - Create a Java class in Eclipse as discussed in previous lessons.

Step 2 - Give it a name as, StringUtils.

StringUtils.java

package com.hubberspot.junit5.assertions;
public class StringUtils {

public static String reverse(String input) {

if(input == null) {
return null;
}

if(input.length() == 0) {
return "";
}

char[] charArray = input.toCharArray();


int start = 0;
int end = input.length() - 1;

while(start < end) {


char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
start++;
end--;
}

return new String(charArray);


}

Class Under Test - StringUtils #


StringUtils is our class under test. It has one method as, reverse() . This
method takes in a String and returns reverse of it.

For example -

1. If we provide input String as, “ABCD”, it returns back “DCBA”.

2. If we provide input String as, “Student”, it returns back “tnedutS”.

3. If we provide input String as, null, it returns back null.

4. If we provide input String as, “”, it returns back “” String.

Step 3 - Create a test class by name, “StringUtilsTest1”. This test class will
demonstrate all overloaded assertEquals() methods.

StringUtilsTest1.java

package com.hubberspot.junit5.assertions;

import static org.junit.jupiter.api.Assertions.*;


import java.util.function.Supplier;
import org.junit.jupiter.api.Test;

class StringUtilsTest1 {

// ******** assertEquals Example - Start **********

@Test
void givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() {
String actual = StringUtils.reverse((""));
String expected = "";

// assertEquals without message


assertEquals(expected, actual);
}

@Test
void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned() {
String actual = StringUtils.reverse(("ABCD"));
String expected = "DBCA";

String message = "assertEquals failed";


// assertEquals with message
assertEquals(expected, actual, message);
}

@Test
void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned2() {
String actual = StringUtils.reverse(("1234"));
String expected = "2314";

Supplier<String> messageSupplier = () -> "assertEquals failed";


// assertEquals with Java 8 Supplier<String>
assertEquals(expected, actual, messageSupplier);
}

// ******** assertEquals Example - End **********


}

StringUtilsTest1.java

StringUtils.java

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.*;

import java.util.function.Supplier;
import org.junit.jupiter.api.Test;

class StringUtilsTest1 {

// ******** assertEquals Example - Start **********

@Test
void givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() {
String actual = StringUtils.reverse((""));
String expected = "";
// assertEquals without message
assertEquals(expected, actual);

@Test
void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned() {
String actual = StringUtils.reverse(("ABCD"));
String expected = "DBCA";

String message = "assertEquals failed";


// assertEquals with message
assertEquals(expected, actual, message);
}

@Test
void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned2() {
String actual = StringUtils.reverse(("1234"));
String expected = "2314";

Supplier<String> messageSupplier = () -> "assertEquals failed";


// assertEquals with Java 8 Supplier<String>
assertEquals(expected, actual, messageSupplier);
}

// ******** assertEquals Example - End **********


}

Step 4 - Run StringUtilsTest1 class as Junit Test.

Output #

Explanation - #
The order of execution of test cases depends on Junit 5. In StringUtilsTest1
class, there are 3 @Test methods:-

1. givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() - It
tests the scenario that when is provided to reverse() method of
StringUtils class, then “” is returned. Here, return value is empty string.

So, on line 18 providing assertEquals() asserts that expected value and


actual value returned are equal. Thus, it passes the Junit test case because
our expected value which is “” and actual value returned are equal.

2. givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned - It
tests the scenario that when ABCD is provided to reverse() method of
StringUtils class, then DCBA is returned. Here, return value is DCBA. So,
on line 28 providing assertEquals() asserts that expected value and
actual value returned are equal. Thus, it fails the Junit test case because
expected value is DBCA and actual value returned is DCBA.

In this test case, we are using overloaded assertEquals() method, which


takes String message as second argument. As, this test case doesn’t
satisfy assertion condition, it fails and give " AssertionFailedError:
assertEquals failed ==> expected: <DBCA> but was: <DCBA>.

3. givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned2 -
It tests the scenario that when 1234 is provided to reverse() method of
StringUtils class, then 4321 is returned. Here, return value is 4321. So, on
line 38 providing assertEquals() asserts that expected value and actual
value returned are equal. Thus, it fails the Junit test case because
expected value is 2314 and actual value returned is 4321.

In this test case, we are using overloaded assertEquals() method, which


takes Supplier<String> messageSupplier as second argument. As, this test
case doesn’t satisfy assertion condition, it fails and give
" AssertionFailedError: assertEquals failed ==> expected: <2314> but was:
<4321>. It gives AssertionFailedError followed by lazily evaluates String
message we provide to assertEquals() method, as lambda expression.

Though the actual value above returned from reverse() method is correct,
but even if we provide the wrong expected value test case will fail.

Below code will pass all above test cases.

StringUtilsTest1.java
StringUtils.java

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.*;

import java.util.function.Supplier;
import org.junit.jupiter.api.Test;

class StringUtilsTest1 {

// ******** assertEquals Example - Start **********

@Test
void givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() {
String actual = StringUtils.reverse((""));
String expected = "";

// assertEquals without message


assertEquals(expected, actual);
}

@Test
void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned() {
String actual = StringUtils.reverse(("ABCD"));
String expected = "DCBA";

String message = "assertEquals failed";


// assertEquals with message
assertEquals(expected, actual, message);
}

@Test
void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned2() {
String actual = StringUtils.reverse(("1234"));
String expected = "4321";

Supplier<String> messageSupplier = () -> "assertEquals failed";


// assertEquals with Java 8 Supplier<String>
assertEquals(expected, actual, messageSupplier);
}

// ******** assertEquals Example - End **********


}

You can perform code changes to above code widget, run and practice
different outcomes.

In the next lesson, we will look into assertNotEquals() assertion.


assertNotEquals() method

This lesson demonstrates how to use assertNotEquals() method in JUnit 5 to assert test conditions.

WE'LL COVER THE FOLLOWING

• assertNotEquals() method
• Demo
• Class Under Test - StringUtils
• Output
• Explanation -

assertNotEquals() method #
Assertions API provide static assertNotEquals() method. This method helps us
in validating that actual and expected values are not equal. This method uses
equals() to assert the in-equality of actual and expected value.

If the actual value is not equal to expected value then the test case will
pass.
If the actual value is equal to expected value then the test case will fail.

There are basically three useful overloaded methods for assertNotEquals:-

public static void assertNotEquals(Object expected, Object actual)

public static void assertNotEquals(Object expected, Object actual, String message)

public static void assertNotEquals(Object expected, Object actual, Supplier<String> messageSu

1. assertNotEquals(Object expected, Object actual) - It assert whether


expected and actual value are not equal.

2. assertNotEquals(Object expected, Object actual, String message) - It


asserts whether expected and actual value are not equal. In case, if the

expected value is equal to actual value then the test case will fail with the
provided message.

3. assertNotEquals(Object expected, Object actual, Supplier<String>


messageSupplier) - It assert whether expected and actual value are not
equal. In case, if the expected value is equal to actual value then test case
will fail with the provided message through Supplier function. The main
advantage of using Supplier function is that it lazily evaluates to String
only when the test case fails.

JUnit 5 Assertions - assertNotEquals method


‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬

assertNotEquals method

Demo #
Step 1 - Create a Java class in Eclipse as discussed in previous lessons.

Step 2 - Give it a name as, StringUtils.

StringUtils.java

package com.hubberspot.junit5.assertions;
public class StringUtils {

public static String reverse(String input) {

if(input == null) {
return null;
}

if(input.length() == 0) {
return "";
}

char[] charArray = input.toCharArray();


int start = 0;
int end = input.length() - 1;

while(start < end) {


char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
start++;
end--;
}

return new String(charArray);


}

Class Under Test - StringUtils #


StringUtils is our class under test. It has one method as, reverse() . This
method takes in a String and returns reverse of it.

For example -

1. If we provide input String as, “ABCD”, it returns back “DCBA”.

2. If we provide input String as, “Student”, it returns back “tnedutS”.

3. If we provide input String as, null, it returns back null.

4. If we provide input String as, “”, it returns back “” String.

Step 3 - Create a test class by name, “StringUtilsTest2”. This test class will
demonstrate all overloaded assertNotEquals() methods.

StringUtilsTest2.java

StringUtils.java
package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.*;

import java.util.function.Supplier;
import org.junit.jupiter.api.Test;

class StringUtilsTest2 {

// ******** assertNotEquals Example - Start **********

@Test
void givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() {
String actual = StringUtils.reverse((""));
String expected = "1234";

// assertNotEquals without message


assertNotEquals(expected, actual);
}

@Test
void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned() {
String actual = StringUtils.reverse(("ABCD"));
String expected = "DCBA";

String message = "assertNotEquals failed";


// assertNotEquals with message
assertNotEquals(expected, actual, message);
}

@Test
void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned2() {
String actual = StringUtils.reverse(("1234"));
String expected = "4321";

Supplier<String> messageSupplier = () -> "assertNotEquals failed";


// assertNotEquals with Java 8 Supplier<String>
assertNotEquals(expected, actual, messageSupplier);
}

// ******** assertNotEquals Example - End **********


}

You can perform code changes to above code widget, run and practice
different outcomes.

Step 4 - Run StringUtilsTest2 class as Junit Test.

Output #
Explanation - #
The order of execution of test cases depends on Junit 5. In StringUtilsTest1
class, there are 3 @Test methods:-

1. givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() - It
tests the scenario that when “” is provided to reverse() method of
StringUtils class, then “” is returned. Here, return value is “”. So, on line
18 providing assertNotEquals() asserts that expected value and actual
value returned not are equal. Thus, it passes the Junit test case because
our expected value which is “1234” and actual value returned are not
equal.

2. givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned - It
tests the scenario that when ABCD is provided to reverse() method of
StringUtils class, then DCBA is returned. Here, return value is DCBA. So,
on line 28 providing assertNotEquals() asserts that expected value and
actual value returned are not equal. Thus, it fails the Junit test case
because expected value is DBCA and actual value returned is DCBA.

In this test case, we are using overloaded assertNotEquals() method,


which takes String message as second argument. As, this test case doesn’t
satisfy assertion condition, it fails and give " AssertionFailedError:
assertNotEquals failed ==> expected: not equal but was: <DCBA>.

3. givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned2 -
It tests the scenario that when 1234 is provided to reverse() method of
StringUtils class, then 4321 is returned. Here, return value is 4321. So, on
line 38 providing assertNotEquals() asserts that expected value and
actual value returned are not equal. Thus, it fails the Junit test case
because expected value is 4321 and actual value returned is 4321.
In this test case, we are using overloaded assertNotEquals() method,
which takes Supplier<String> messageSupplier as second argument. As,
this test case doesn’t satisfy assertion condition, it fails and give
" AssertionFailedError: assertEquals failed ==> expected: not equal but
was: <4321>. It gives AssertionFailedError followed by lazily evaluates
String message we provide to assertNotEquals() method, as lambda
expression.

Though, actual value above returned from reverse() method is correct, but
even if we provide the wrong expected value test case will fail.

Below code will pass all the above test cases.

StringUtilsTest2.java

StringUtils.java

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.*;

import java.util.function.Supplier;
import org.junit.jupiter.api.Test;

class StringUtilsTest2 {

// ******** assertNotEquals Example - Start **********

@Test
void givenEmptyString_whenReverseIsCalled_thenEmptyStringIsReturned() {
String actual = StringUtils.reverse((""));
String expected = "1234";

// assertNotEquals without message


assertNotEquals(expected, actual);
}

@Test
void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned() {
String actual = StringUtils.reverse(("ABCD"));
String expected = "DCBA";

String message = "assertNotEquals failed";


// assertNotEquals with message
assertNotEquals(expected, actual, message);
}

@Test
void givenNonNullString_whenReverseIsCalled_thenReversedStringIsReturned2() {
String actual = StringUtils.reverse(("1234"));
String expected = "4321";

Supplier<String> messageSupplier = () -> "assertNotEquals failed";


// assertNotEquals with Java 8 Supplier<String>
assertNotEquals(expected, actual, messageSupplier);
}

// ******** assertNotEquals Example - End **********


}

In the next lesson, we will look into fail() assertion.


fail() method

This lesson demonstrates the importance of the fail method in JUnit 5 Assertions API.

WE'LL COVER THE FOLLOWING

• fail() method

fail() method #
Assertions API provide static fail() method. As soon as, any @Test method
encounters fail() static method, it will fail the test case. The primary usages
of fail() method are as follows -

It gives a piece of meaningful information to the programmer writing a


test, that test case is in progress and still needs to be implemented.
It can be used to verify that an actual exception is thrown. Usually based
on some input when test case expects an exception at a certain line,
providing fail() below that line will verify that exception was not
thrown as code execution reached fail() method line. Thus, it explicitly
fails the test case.

There are basically five useful overloaded methods to fail:-

public static void fail()

public static void fail(String message)

public static void fail(Supplier<String> messageSupplier)

public static void fail(Throwable throwable)

public static void fail(String message, Throwable throwable)

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.fail;


import org.junit.jupiter.api.Test;

public class FailAssertionDemo {

// usage 1 - @Test not implemented with fail()


@Test
public void testMethodYetNotImplemented() {
fail();
}

// usage 2 - @Test not implemented with fail(String message)


@Test
public void testMethodYetNotImplemented1() {
fail("@Test method not yet implemented !!!");
}

// usage 3 - @Test not implemented with fail(Supplier<String> messageSupplier)


@Test
public void testMethodYetNotImplemented2() {
fail(() -> "@Test method not yet implemented !!!");
}

// usage 4 - @Test not implemented with fail(Throwable throwable)


@Test
public void testMethodYetNotImplemented3() {
fail(new RuntimeException("@Test method not yet implemented !!!"));
}

// usage 5 - @Test not implemented with fail(String message, Throwable throwable)


@Test
public void testMethodYetNotImplemented4() {
fail("@Test method not yet implemented !!!", new RuntimeException("Failed exp
}

// usage 6 - It can be used to verify that an actual exception is thrown


@Test
public void testActualExceptionThrown() {
try {
methodThatShouldThrowException();
fail("Exception not thrown !!!");
} catch (UnsupportedOperationException e) {
// test case passed
}
}

private void methodThatShouldThrowException() {


throw new UnsupportedOperationException(); // uncomment this line to will fai
}

You can perform code changes to above code widget, run and practice
different outcomes.
Step 4 - Run FailedAssertionDemo.java class as Junit Test.

In the next lesson, we will look into assertTrue() and assertFalse()


assertion.
assertTrue() method

This lesson demonstrates how to use assertTrue method in JUnit 5 to assert test conditions.

WE'LL COVER THE FOLLOWING

• assertTrue() method
• Demo
• Explanation -

assertTrue() method #
Assertions API provide static assertTrue() method. This method helps us in
validating that the actual value supplied to it is true .

If the actual value is true then test case will pass.


If the actual value is not true then test case will fail.

There are basically six useful overloaded methods for assertTrue:-

public static void assertTrue(boolean condition)

public static void assertTrue(boolean condition, String message)

public static void assertTrue(boolean condition, Supplier<String> messageSupplier)

public static void assertTrue(BooleanSupplier booleanSupplier)

public static void assertTrue(BooleanSupplier booleanSupplier, String message)

public static void assertTrue(BooleanSupplier booleanSupplier, Supplier<String> messageSuppli


JUnit 5 Assertions - assertTrue method
‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬

Demo #
Let’s look into the usage of the above methods:-

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

public class AssertTrueDemo {

@Test
public void testAssertTrueWithTrueCondition() {
boolean trueValue = true;
assertTrue(trueValue);
}

@Test
public void testAssertTrueWithFalseCondition() {
boolean falseValue = false;
assertTrue(falseValue);
}

@Test
public void testAssertTrueWithFalseConditionAndMessage() {
boolean falseValue = false;
assertTrue(falseValue, "The actual value is false");
}
@Test
public void testAssertTrueWithFalseConditionAndMessageSupplier() {
boolean falseValue = false;
assertTrue(falseValue, () -> "The actual value is false");
}

@Test
public void testAssertTrueWithBooleanSupplier() {
boolean trueValue = true;
assertTrue(() -> trueValue);
}

@Test
public void testAssertTrueWithBooleanSupplierAndMessage() {
boolean falseValue = false;
assertTrue(() -> falseValue, "The actual value is false");
}

@Test
public void testAssertTrueWithBooleanSupplierAndMessageSupplier() {
boolean falseValue = false;
assertTrue(() -> falseValue, () -> "The actual value is false");
}
}

You can perform code changes to above code widget, run and practice
different outcomes.

Run AssertTrueDemo class as JUnit Test.

Explanation - #
In AssertTrueDemo class there are 7 @Test methods. These 7 methods
demonstrate the working of the above 6 overloaded methods of assertTrue :-

1. testAssertTrueWithTrueCondition() - It asserts the boolean value


provided to assertTrue() method. Here, the actual value passed to it is
true . Thus, it passes the Junit test case because assertTrue asserts that
value passed to it should be true.

2. testAssertTrueWithFalseCondition() - It asserts the boolean value


provided to assertTrue() method. Here, actual value passed to it is
false . Thus, it fails the Junit test case with AssertionFailedError:
expected: <true> but was: <false> because value passed to assertTrue
method is false.

3. testAssertTrueWithFalseConditionAndMessage - It asserts the boolean value


provided to assertTrue() method. Here, actual value passed to it is
false . Thus, it fails the Junit test case with AssertionFailedError: The
actual value is false ==> expected: <true> but was: <false> because value
passed to assertTrue method is false. It gives AssertionFailedError
followed String message we provide to assertTrue() method.

4. testAssertTrueWithFalseConditionAndMessageSupplier - It asserts the


boolean value provided to assertTrue() method. Here, actual value
passed to it is false . Thus, it fails the Junit test case with
AssertionFailedError: The actual value is false ==> expected: <true> but
was: <false> because value passed to assertTrue method is false. It
gives AssertionFailedError followed by lazily evaluates String message
we provide to assertTrue() method, as lambda expression.

5. testAssertTrueWithBooleanSupplier() - It asserts the boolean value


provided to assertTrue() method through BooleanSupplier functional
interface. Here, actual value passed to it is true . Thus, it passes the JUnit
test case because assertTrue asserts that value passed to it should be
true.

6. testAssertTrueWithBooleanSupplierAndMessage - It asserts the boolean


value provided to assertTrue() method through BooleanSupplier
functional interface. Here, actual value passed to it is false . Thus, it fails
the Junit test case with AssertionFailedError: The actual value is false
==> expected: <true> but was: <false> because value passed to assertTrue
method is false. It gives AssertionFailedError followed String message
we provide to assertTrue() method.
7. testAssertTrueWithBooleanSupplierAndMessageSupplier - It asserts the
boolean value provided to assertTrue() method through
BooleanSupplier functional interface. Here, actual value passed to it is
false . Thus, it fails the Junit test case with AssertionFailedError: The
actual value is false ==> expected: <true> but was: <false> because value
passed to assertTrue method is false. It gives AssertionFailedError
followed by lazily evaluates String message we provide to assertTrue()
method, as lambda expression.

In the next lesson, we will look into assertFalse() assertion.


assertFalse method

This lesson demonstrates how to use assertFalse method in JUnit 5 to assert test conditions.

WE'LL COVER THE FOLLOWING

• assertFalse() method
• Demo
• Explanation -

assertFalse() method #
Assertions API provide static assertFalse() method. This method helps us in
validating that the actual value supplied to it is false .

If the actual value is false then test case will pass.


If the actual value is true then test case will fail.

There are basically six useful overloaded methods for assertFalse -

public static void assertFalse(boolean condition)

public static void assertFalse(boolean condition, String message)

public static void assertFalse(boolean condition, Supplier<String> messageSupplier)

public static void assertFalse(BooleanSupplier booleanSupplier)

public static void assertFalse(BooleanSupplier booleanSupplier, String message)

public static void assertFalse(BooleanSupplier booleanSupplier, Supplier<String> messageSuppl


JUnit 5 Assertions - assertFalse method
‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬

assertFalse() method

Demo #
Let’s look into the usage of the above methods.

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertFalse;

import org.junit.jupiter.api.Test;

public class AssertFalseDemo {

@Test
public void testAssertFalseWithFalseCondition() {
boolean falseValue = false;
assertFalse(falseValue);
}

@Test
public void testAssertFalseWithTrueCondition() {
boolean trueValue = true;
assertFalse(trueValue);
}

@Test
public void testAssertFalseWithTrueConditionAndMessage() {
boolean trueValue = true;
assertFalse(trueValue, The actual value is true );
}

@Test
public void testAssertFalseWithTrueConditionAndMessageSupplier() {
boolean trueValue = true;
assertFalse(trueValue, () -> "The actual value is true");
}

@Test
public void testAssertFalseWithBooleanSupplier() {
boolean falseValue = false;
assertFalse(() -> falseValue);
}

@Test
public void testAssertFalseWithBooleanSupplierAndMessage() {
boolean trueValue = true;
assertFalse(() -> trueValue, "The actual value is true");
}

@Test
public void testAssertFalseWithBooleanSupplierAndMessageSupplier() {
boolean trueValue = true;
assertFalse(() -> trueValue, () -> "The actual value is true");
}
}

You can perform code changes to above code widget, run and practice
different outcomes.

Run AssertFalseDemo class as JUnit Test.

Explanation - #
In AssertFalseDemo class, there are 7 @Test methods. These 7 methods
demonstrate the working of the above 6 overloaded methods of assertFalse .
1. testAssertFalseWithFalseCondition() - It asserts the boolean value
provided to assertFalse() method. Here, the actual value passed to it is

false . Thus, it passes the Junit test case because assertFalse asserts that
value passed to it should be false.

2. testAssertFalseWithTrueCondition() - It asserts the boolean value


provided to assertFalse() method. Here, actual value passed to it is
true . Thus, it fails the Junit test case with AssertionFailedError:
expected: <false> but was: <true> because value passed to assertFalse
method is true .

3. testAssertFalseWithTrueConditionAndMessage - It asserts the boolean value


provided to assertFalse() method. Here, actual value passed to it is
true . Thus, it fails the Junit test case with AssertionFailedError: The
actual value is true ==> expected: <false> but was: <true> because value
passed to assertFalse method is true. It gives AssertionFailedError
followed String message we provide to assertFalse() method.

4. testAssertFalseWithTrueConditionAndMessageSupplier - It asserts the


boolean value provided to assertFalse() method. Here, actual value
passed to it is true . Thus, it fails the Junit test case with
AssertionFailedError: The actual value is true ==> expected: <false> but
was: <true>** because value passed to assertFalse method is true. It
gives AssertionFailedError followed by lazily evaluated String message
we provide to assertFalse() method, as lambda expression.

5. testAssertFalseWithBooleanSupplier() - It asserts the boolean value


provided to assertFalse() method through BooleanSupplier functional
interface. Here, actual value passed to it is false . Thus, it passes the JUnit
test case because assertFalse asserts that value passed to it should be
false.

6. testAssertFalseWithBooleanSupplierAndMessage - It asserts the boolean


value provided to assertFalse() method through BooleanSupplier
functional interface. Here, actual value passed to it is true . Thus, it fails
the Junit test case with AssertionFailedError: The actual value is true
==> expected: <false> but was: <true> because value passed to
assertFalse method is true. It gives AssertionFailedError followed
String message we provide to assertFalse() method.
7. testAssertFalseWithBooleanSupplierAndMessageSupplier - It asserts the
boolean value provided to assertFalse() method through
BooleanSupplier functional interface. Here, actual value passed to it is
true . Thus, it fails the Junit test case with AssertionFailedError: The
actual value is true ==> expected: <false> but was: <true> because value
passed to assertFalse method is true. It gives AssertionFailedError
followed by lazily evaluated String message we provide to assertFalse()
method, as lambda expression.

In the next lesson, we will look into assertSame() and assertNotSame()


assertions.
assertSame() method

This lesson demonstrates how to use assertSame method in JUnit 5 to assert test conditions.

WE'LL COVER THE FOLLOWING

• assertSame() method
• Demo
• Explanation -

assertSame() method #
Assertions API provide static assertSame() method. This method helps us in
validating that expected and actual refer to the exact same object. JUnit uses
== operator to perform this assert.

If the actual and expected value refers to the same object then the test
case will pass.
If the actual and expected value does not refer to the same object then the
test case will fail.

There are basically three useful overloaded methods for assertSame:-

public static void assertSame(Object expected, Object actual)

public static void assertSame(Object expected, Object actual, String message)

public static void assertSame(Object expected, Object actual, Supplier<String> messageSupplie

Demo #
Let’s look into the usage of the above methods:-

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertSame;


import org.junit.jupiter.api.Test;

public class AssertSameDemo {

@Test
public void testAssertSameWithSameObject() {
String actual = "hello";
String expected = "hello";
assertSame(expected, actual);
}

@Test
public void testAssertSameWithDifferentObject() {
String actual = "hello";
String expected = "hell";
assertSame(expected, actual);
}

@Test
public void testAssertSameWithDifferentObjectAndMessage() {
String actual = "hello";
String expected = "hell";
assertSame(expected, actual, "The actual value is not same as expected value"
}

@Test
public void testAssertSameWithDifferentObjectAndMessageSupplier() {
String actual = "hello";
String expected = "hell";
assertSame(expected, actual, () -> "The actual value is not same as expected
}
}

Run AssertSameDemo class as JUnit Test.

Explanation - #
In the AssertSameDemo class, there are 4 @Test methods. These 4 methods
demonstrate the working of the above 3 overloaded methods of assertSame :-

1. testAssertSameWithSameObject() - It asserts that actual value refers to


same expected object. Here, the expected value and actual value passed

to assertSame() is hello . Thus, it passes the Junit test case because


assertSame finds actual and expected objects as same.

2. testAssertSameWithDifferentObject() - It asserts that actual value refers


to same expected object. Here, the expected value and actual value
passed to assertSame() are hell and hello . Thus, it fails the Junit test
case with AssertionFailedError: expected: <hell> but was: <hello>
because hell and hello are not same String objects.

3. testAssertSameWithDifferentObjectAndMessage - It asserts that actual value


refers to same expected object. Here, the expected value and actual value
passed to assertSame() are hell and hello . Thus, it fails the Junit test
case with AssertionFailedError: The actual value is not same as expected
value ==> expected: <hell> but was: <hello> because hell and hello are not
same String objects. It gives AssertionFailedError followed by String
message we provide to assertSame() method.

4. testAssertTrueWithFalseConditionAndMessageSupplier - It asserts that


actual value refers to same expected object. Here, the expected value and
actual value passed to assertSame() are hell and hello . Thus, it fails the
Junit test case with AssertionFailedError: The actual value is not same as
expected value ==> expected: <hell> but was: <hello> because hell and
hello are not same String objects. It gives AssertionFailedError followed
by lazily evaluated String message we provide to assertSame() method,
as lambda expression.

In the next lesson, we will look into assertNotSame() assertion.


assertNotSame() method

This lesson demonstrates how to use assertNotSame method in JUnit 5 to assert test conditions.

WE'LL COVER THE FOLLOWING

• assertNotSame() method
• Demo
• Explanation -

assertNotSame() method #
Assertions API provide static assertNotSame() method. This method helps us
in validating that expected and actual do not refer to the exact same object.
JUnit uses == operator to perform this assert.

If the actual and expected value refers to the same object then the test
case will fail.
If the actual and expected value does not refer to the same object then the
test case will pass.

There are basically three useful overloaded methods for assertNotSame:-

public static void assertNotSame(Object actual)

public static void assertNotSame(Object actual, String message)

public static void assertNotSame(Object actual, Supplier<> messageSupplier)

Demo #
Let’s look into the usage of the above methods:-

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertNotSame;


import org.junit.jupiter.api.Test;

public class AssertNotSameDemo {

@Test
public void testAssertNotSameWithDifferentObject() {
String actual = "hello";
String expected = "hell";
assertNotSame(expected, actual);
}

@Test
public void testAssertNotSameWithSameObject() {
String actual = "hello";
String expected = "hello";
assertNotSame(expected, actual);
}

@Test
public void testAssertNotSameWithSameObjectAndMessage() {
String actual = "hello";
String expected = "hello";
assertNotSame(expected, actual, "The actual value is same as expected value")
}

@Test
public void testAssertNotSameWithSameObjectAndMessageSupplier() {
String actual = "hello";
String expected = "hello";
assertNotSame(expected, actual, () -> "The actual value is same as expected v
}
}

Run AssertNotSameDemo class as JUnit Test.

Explanation - #
In the AssertNotSameDemo class, there are 4 @Test methods. These 4 methods
demonstrate the working of the above 3 overloaded methods of
assertNotSame :-
1. testAssertNotSameWithDifferentObject - It asserts that actual value does
not refer to same expected object. Here, the expected value and actual

value passed to assertNotSame() are hell and hello . Thus, it passes the
Junit test case because assertNotSame finds actual and expected objects
not same.

2. testAssertNotSameWithSameObject - It asserts that actual value does not


refer to same expected object. Here, the expected value and actual value
passed to assertNotSame() is hello . Thus, it fails the Junit test case with
AssertionFailedError: expected: not same but was: <hello> because
‘hello’ and ‘hello’ are same String objects.

3. testAssertNotSameWithSameObjectAndMessage - It asserts that actual value


does not refer to same expected object. Here, the expected value and
actual value passed to assertNotSame() is hello . Thus, it fails the Junit
test case with AssertionFailedError: The actual value is same as
expected value ==> expected: not same but was: <hello> because ‘hello’
and ‘hello’ are same String objects. It gives AssertionFailedError
followed by String message we provide to assertNotSame() method.

4. testAssertNotSameWithSameObjectAndMessageSupplier - It asserts that actual


value does not refer to same expected object. Here, the expected value
and actual value passed to assertNotSame() is hello . Thus, it fails the
Junit test case with AssertionFailedError: The actual value is same as
expected value ==> expected: not same but was: <hello> because hello
and hello are same String objects. It gives AssertionFailedError followed
by lazily evaluated String message we provide to assertNotSame()
method, as lambda expression.

In the next lesson, we will look into assertArrayEquals() and


assertIterableEquals() assertions.
assertArrayEquals() method

This lesson demonstrates how to use assertArrayEquals method in JUnit 5 to assert test conditions.

WE'LL COVER THE FOLLOWING

• assertArrayEquals() method
• Demo
• Explanation -

assertArrayEquals() method #
Assertions API provide static assertArrayEquals() method. This method helps
us in validating that expected and actual arrays are equal. It has many
overloaded methods to assert different types of array objects.

If the actual and expected arrays are equal then the test case will pass.
If the actual and expected arrays are not equal then the test case will fail.

There are basically three useful overloaded methods for assertArrayEquals:-

public static void assertArrayEquals(int[] expected, int[] actual)

public static void assertArrayEquals(int[] expected, int[] actual, String message)

public static void assertArrayEquals(int[] expected, int[] actual, Supplier<String> messageSu

// Many more same methods for different data types

Demo #
Let’s look into the usage of the above methods:-
JUnit 5 Assertions - assertArrayEquals method
‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬

assertArrayEquals method

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import org.junit.jupiter.api.Test;

public class AssertArrayEqualsDemo {

@Test
public void testAssertArrayEqualsForEqualArrays() {
int[] expected = {1,2,3,4};
int[] actual = {1,2,3,4};
assertArrayEquals(expected, actual);
}

@Test
public void testAssertArrayEqualsForNotEqualArrays() {
int[] expected = {1,2,3,4};
int[] actual = {1,2,3};
assertArrayEquals(expected, actual, "Arrays are not equal.");
}

@Test
public void testAssertArrayEqualsForEqualArraysWithDifferentOrder() {
int[] expected = {1,2,4,3};
int[] actual = {1,2,3,4};
assertArrayEquals(expected, actual, () -> "Arrays order is different");
}
}
Run AssertArrayEqualsDemo class as JUnit Test.

Explanation - #
In the AssertArrayEqualsDemo class, there are 3 @Test methods. These 3
methods demonstrate the working of the above 3 overloaded methods of
assertArrayEquals :-

1. testAssertArrayEqualsForEqualArrays() - It asserts that actual and


expected arrays are equal. Here, the expected array, {1,2,3,4} and actual
array, {1,2,3,4} are passed to assertArrayEquals() . Thus, it passes the
Junit test case because assertArrayEquals() finds actual and expected
arrays to be equal.

2. testAssertArrayEqualsForNotEqualArrays() - It asserts that actual and


expected arrays are equal. Here, the expected array, {1,2,3,4} and actual
array, {1,2,3} are passed to assertArrayEquals() . Thus, it fails the Junit
test case with AssertionFailedError: Arrays are not equal. ==> array
lengths differ, expected: <4> but was: <3> because assertArrayEquals()
finds actual and expected arrays not equal. It gives AssertionFailedError
followed by String message we provide to assertArrayEquals() method.

3. testAssertArrayEqualsForEqualArraysWithDifferentOrder() - It asserts that


actual and expected arrays are equal. Here, the expected array, {1,2,4,3}
and actual array, {1,2,3,4} are passed to assertArrayEquals() . Thus, it fails
the Junit test case with AssertionFailedError: Arrays order is different
==> array contents differ at index [2], expected: <4> but was: <3> because
though contents of array are same they are not in same order. It gives
AssertionFailedError followed by lazily evaluated String message we
provide to assertArrayEquals() method, as lambda expression.

In the next lesson, we will look into assertIterableEquals() assertion.


assertIterableEquals method

This lesson demonstrates how to use assertIterableEquals method in JUnit 5 to assert test conditions.

WE'LL COVER THE FOLLOWING

• assertIterableEquals() method
• Demo
• Explanation -

assertIterableEquals() method #
Assertions API provide static assertIterableEquals() method. This method
helps us in validating that expected and actual iterables are deeply equal.
By, deeply equal we mean that number and order of elements in the collection
must be the same, as well as iterated elements must be equal.

There are basically three useful overloaded methods for assertIterableEquals:-

public static void assertIterableEquals(Iterable<?> expected, Iterable> actual)

public static void assertIterableEquals(Iterable<?> expected, Iterable> actual, String messag

public static void assertIterableEquals(Iterable<?> expected, Iterable> actual, Supplier<Stri

Demo #
Let’s look into the usage of the above methods:-
assertIterableEquals method

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertIterableEquals;

import java.util.ArrayList;
import java.util.Arrays;

import org.junit.jupiter.api.Test;

public class AssertIterableEqualsDemo {

@Test
public void testAssertIterableEqualsForEqualIterables() {
Iterable<Integer> expected = new ArrayList<>(Arrays.asList(1,2,3,4));
Iterable<Integer> actual = new ArrayList<>(Arrays.asList(1,2,3,4));
assertIterableEquals(expected, actual);
}

@Test
public void testAssertIterableEqualsForNotEqualIterables() {
Iterable<Integer> expected = new ArrayList<>(Arrays.asList(1,2,3,4));
Iterable<Integer> actual = new ArrayList<>(Arrays.asList(1,2,3));
assertIterableEquals(expected, actual, "Iterables are not equal.");
}

@Test
public void testAssertIterableEqualsForEqualIterablesWithDifferentOrder() {
Iterable<Integer> expected = new ArrayList<>(Arrays.asList(1,2,3,4));
Iterable<Integer> actual = new ArrayList<>(Arrays.asList(1,2,4,3));
assertIterableEquals(expected, actual, () -> "Iterables order is different");
}
}

Run AssertIterableEqualsDemo class as JUnit Test.

Explanation - #
In the AssertIterableEqualsDemo class, there are 3 @Test methods. These 3
methods demonstrate the working of the above 3 overloaded methods of
assertIterableEquals :-

1. testAssertIterableEqualsForEqualIterables() - It asserts that actual and


expected iterables are equal. Here, the expected iterable is ArrayList with
four elements as, {1,2,3,4} and actual iterable is ArrayList with four
elements as, {1,2,3,4}. Thus, it passes the Junit test case because
assertIterableEquals finds actual and expected iterables to be equal.

2. testAssertIterableEqualsForNotEqualIterables() - It asserts that actual


and expected iterables are equal. Here, the expected iterable is arraylist
with four elements as, {1,2,3,4} and actual iterable is arraylist with four
elements as, {1,2,3}. Thus, it fails the Junit test case with
AssertionFailedError: Iterables are not equal. ==> iterable lengths differ,
expected: <4> but was: <3> because assertIterableEquals finds actual
and expected iterables not equal. It gives AssertionFailedError followed
by String message we provide to assertIterableEquals() method.

3. testAssertIterableEqualsForEqualIterablesWithDifferentOrder() - It
asserts that actual and expected iterables are equal. Here, the expected
iterable is arraylist with four elements as, {1,2,3,4} and actual iterable is
arraylist with four elements as, {1,2,4,3}. Thus, it fails the Junit test case
with AssertionFailedError: Iterables order is different ==> iterable
contents differ at index [2], expected: <3> but was: <4> because though

contents of iterables are same they are not in same order. It gives
AssertionFailedError followed by lazily evaluated String message we
provide to assertIterableEquals() method, as lambda expression.

In the next lesson, we will look into assertThrows() assertion.


assertThrows() method

This lesson demonstrates how to use assertThrows method in JUnit 5 to assert test conditions.

WE'LL COVER THE FOLLOWING

• assertThrows() method
• Demo

assertThrows() method #
Assertions API provide static assertThrows() method. This method helps in
asserting that execution of the supplied Executable throws an exception of the
expectedType and returns the exception.

If no exception is thrown, or if an exception of a different type is thrown,


this method will fail.
It follows the inheritance hierarchy, so the assert will pass if the expected
type is Exception and actual is RuntimeException .

There are basically three useful overloaded methods for assertThrows:-

public static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executab

public static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executab

public static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executab

Demo #
Let’s look into the usage of the above methods:-
JUnit 5 Assertions - assertThrows method
‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬

assertThrows method

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;

import org.junit.jupiter.api.Test;

public class AssertThrowsDemo {

@Test
public void testAssertThrows() {
assertThrows(ArithmeticException.class, () -> divide(1, 0));
}

@Test
public void testAssertThrowsWithMessage() {
assertThrows(IOException.class, () -> divide(1, 0), "Division by zero !!!");
}

@Test
public void testAssertThrowsWithMessageSupplier() {
assertThrows(IOException.class, () -> divide(1, 0), () -> "Division by zero !
}

private int divide(int a, int b) {


return a / b;
}
}
Run AssertThrowsDemo class as JUnit Test.

In the next lesson, we will look into assertTimeout() and


assertTimeoutPreemptively() assertions.
assertTimeout() method

This lesson demonstrates how to use assertTimeout method in JUnit 5 to assert timeout conditions.

WE'LL COVER THE FOLLOWING

• assertTimeout() method
• Demo

assertTimeout() method #
Assertions API provide static assertTimeout() method. It is used to test long-
running tasks. If given task inside the test case takes more than the specified
duration, then the test will fail.

The executable provided to the test case will be executed in the same thread
as that of the calling code. Also, the execution of the executable will not be
preemptively aborted if the timeout is exceeded.

There are basically three useful overloaded methods for assertTimeout:-

public static void assertTimeout(Duration timeout, Executable executable)

public static void assertTimeout(Duration timeout, Executable executable, String message)

public static void assertTimeout(Duration timeout, Executable executable, Supplier<String> me

Demo #
Let’s look into the usage of the above methods:-
JUnit 5 Assertions - assertTimeout method
‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬

assertTimeout method

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertEquals;


import static org.junit.jupiter.api.Assertions.assertTimeout;

import java.time.Duration;

import org.junit.jupiter.api.Test;

public class AssertTimeoutDemo {


@Test
void timeoutNotExceeded() {
// The following assertion succeeds.
assertTimeout(Duration.ofMinutes(3), () -> {
// Perform task that takes less than 3 minutes.
});
}

@Test
void timeoutNotExceededWithResult() {
// The following assertion succeeds, and returns the supplied object.
String actualResult = assertTimeout(Duration.ofMinutes(3), () -> {
return "result";
});
assertEquals("result", actualResult);
}

@Test
void timeoutNotExceededWithMethod() {
// The following assertion invokes a method reference and returns an object.
String actualGreeting = assertTimeout(Duration.ofMinutes(3), AssertTimeoutDemo::greet
assertEquals("Hello, World!", actualGreeting);

@Test
void timeoutExceeded() {
// The following assertion fails with an error message similar to:
// execution exceeded timeout of 10 ms by 91 ms
assertTimeout(Duration.ofMillis(10), () -> {
// Simulate task that takes more than 10 ms.
Thread.sleep(100);
});
}

private static String greeting() {


return "Hello, World!";
}
}

Run AssertTimeoutDemo class as JUnit Test.

In the next chapter, we will discuss about assertTimeoutPreemptively


assertion.
assertTimeoutPreemptively method

This lesson demonstrates how to use assertTimeoutPreemptively method in JUnit 5 to assert timeout conditions.

WE'LL COVER THE FOLLOWING

• assertTimeoutPreemptively() method
• Demo

assertTimeoutPreemptively() method #
Assertions API provide static assertTimeoutPreemptively() method. It is used
to test long-running tasks. If given task inside the test case takes more than the
specified duration, then the test will fail.

The executable provided to the test case will be executed in the different
thread as that of the calling code. Also, the execution of the executable will be
preemptively aborted if the timeout is exceeded.

Demo #
Let’s look into the usage of the above methods:-
JUnit 5 Assertions - assertTimeoutPreemptively method
‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬

assertTimeoutPreemptively method

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;

import java.time.Duration;

import org.junit.jupiter.api.Test;

public class AssertTimeoutPreemptivelyDemo {


@Test
void timeoutExceededWithPreemptiveTermination() {
// The following assertion fails with an error message similar to:
// execution timed out after 10 ms
assertTimeoutPreemptively(Duration.ofMillis(10), () -> {
// Simulate task that takes more than 10 ms.
Thread.sleep(100);
});
}
}

Run AssertTimeoutPreemptivelyDemo class as JUnit Test.


In the next chapter, we will discuss about JUnit Test Lifecycle callbacks.
@BeforeEach and @AfterEach Annotation

This lesson demonstrates working of two Lifecycle methods annotated with - @BeforeEach and @AfterEach
Annotation.

WE'LL COVER THE FOLLOWING

• @Test and Constructor


• @BeforeEach and @AfterEach

@Test and Constructor #


In Junit 5 for each test, a new instance of test class is created. So, for e.g. if a
class has two @Test methods than two instances of test class will be created,
one for each test. Thus, the constructor of the test class will be called as many
times as there is the number of @Test methods. Let’s look at the demo:-

package io.educative.junit5;

import org.junit.jupiter.api.Test;

public class LifecycleTest {

public LifecycleTest() {
System.out.println("LifecycleTest - Constructor got executed !!!");
}

@Test
public void testOne() {
System.out.println("LifecycleTest - testOne() got executed !!!");
}

@Test
public void testTwo() {
System.out.println("LifecycleTest - testTwo() got executed !!!");
}

}
Output of the test

Here, you can see constructor got called two times because there were two
@Test annotated methods. Thus, it proves that each test runs in its own test
class instance.

@BeforeEach and @AfterEach #


Methods annotated with @BeforeEach and @AfterEach as the name suggests
are called before each and after each @Test methods. So, if in a test class there
are two @Test methods, the @BeforeEach method will be called twice, just
before each @Test method and similarly, the @AfterEach method will be
called twice, just after each @Test method. Let’s look at demo taking previous
test class:-

package io.educative.junit5;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class LifecycleTest {

public LifecycleTest() {
System.out.println("LifecycleTest - Constructor got executed !!!");
}

@BeforeEach
public void beforeEach() {
System.out.println("LifecycleTest - beforeEach() got executed !!!");
}

@Test
public void testOne() {
System.out.println("LifecycleTest - testOne() got executed !!!");
}
@Test
public void testTwo() {
System.out.println("LifecycleTest - testTwo() got executed !!!");

@AfterEach
public void afterEach() {
System.out.println("LifecycleTest - afterEach() got executed !!!");
}

Output of the test

As Junit test class has two @Test methods, it executes each of the test methods
in a separate instance of the test class. Thus, it picks the first @Test method in
random order and -

1. It initializes the test class by calling its constructor.


2. After that, it executes the @BeforeEach annotated method.
3. After that, it executes the @Test method.
4. After that, it executes the @AfterEach annotated method.
5. Then it picks the second @Test method and executes again from step 1 to
4.

Usually, when we have common setup logic across various test cases, the
common initialization code is placed in the @BeforeEach annotated method
and cleaned up in @AfterEach annotated method.
In the next lesson, we will look into @BeforeAll() and @AfterAll lifecycle
callbacks.
@BeforeAll and @AfterAll Annotation

This lesson demonstrates working of two more Lifecycle methods annotated with - @BeforeAll and @AfterAll
Annotation.

WE'LL COVER THE FOLLOWING

• @BeforeAll and @AfterAll

@BeforeAll and @AfterAll #


Methods annotated with @BeforeAll and @AfterAll are static methods
because, as the name suggest they are called once before all and once after all
@Test methods. So, if in a test class there are two @Test methods, the
@BeforeAll method will be called once before all test methods and similarly,
the @AfterAll method will be called once, just after all @Test method gets
finished. Let’s look at demo taking previous lesson test class:-

package io.educative.junit5;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class LifecycleTest {

@BeforeAll
public static void beforeAll() {
System.out.println("LifecycleTest - beforeAll() got executed !!!");
}

public LifecycleTest() {
System.out.println("LifecycleTest - Constructor got executed !!!");
}

@BeforeEach
public void beforeEach() {
System.out.println("LifecycleTest - beforeEach() got executed !!!");
}

@Test
public void testOne() {
System.out.println("LifecycleTest - testOne() got executed !!!");
}

@Test
public void testTwo() {
System.out.println("LifecycleTest - testTwo() got executed !!!");
}

@AfterEach
public void afterEach() {
System.out.println("LifecycleTest - afterEach() got executed !!!");
}

@AfterAll
public static void afterAll() {
System.out.println("LifecycleTest - afterAll() got executed !!!");
}

Output of the test

You can see in the output of the above test class, that @BeforeAll and
@AfterAll has the following properties:-

1. Both are static methods.


2. Both are called once in a test lifecycle.
3. @BeforeAll annotated method being a class level method, it gets called
even before the constructor.
4. @AfterAll annotated method being a class level method, it gets called
after all methods get executed.
5. @BeforeAll annotated method is used where expensive resource
initialization needs to be done such as database connection, server start
etc. This resources that can be used by test methods.
6. @AfterAll annotated method is used where expensive resource clean up
needs to be done such as, database connection terminates, server stop
etc. So that these expensive resources can be cleaned up.

In the next chapter, we will discuss about @DisplayName .


@DisplayName Annotation on Test Class

This lesson demonstrates how to provide custom display names to test class.

WE'LL COVER THE FOLLOWING

• @DisplayName on Test Class

@DisplayName on Test Class #


JUnit 5 has @DisplayName annotation which is used to provide a custom name
for the test class. Usually, By default, JUnit 5 reporting prints the class name in
the IDE test report and also while executing test cases. We can use
@DisplayName annotation to provide a custom name to test class, that makes it
easier to read. Thus, it acts as metadata for our test class.

@DisplayName annotation can take up string having the following things:-

1. It can take spaces between words.


2. It can take special characters.
3. It can take emojis as well.

Let’s look at a demo:-

package io.educative.junit5;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

@DisplayName("Display name with spaces")


public class DisplayNameWithSpaces {

@Test
public void test() {
System.out.println("test method got executed!!!");
}
}
@DisplayName with spaces

package io.educative.junit5;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

@DisplayName("Display name with !@#$%^&*()_+~`╯°□°)╯ special character")


public class DisplayNameWithSpecialCharacters {

@Test
public void test() {
System.out.println("test method got executed!!!");
}
}

@DisplayName with special characters

package io.educative.junit5;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

@DisplayName("Display name with 😱 emojis")


public class DisplayNameWithEmojis {

@Test
public void test() {
System.out.println( test method got executed!!! );
}
}

@DisplayName with Emojis

Instead of printing actual test class in the Junit tab and reports, it prints string
provided in @DisplayName annotation.

It actually provides a textual representation of what actually test class does.

In the next lesson, we will discuss about @DisplayName on test methods.


@DisplayName Annotation on Test Methods

This lesson demonstrates how to provide custom display names to test methods.

WE'LL COVER THE FOLLOWING

• @DisplayName on @Test Methods

@DisplayName on @Test Methods #


JUnit 5 @DisplayName annotation is also used to provide a custom name for the
@Test methods. Usually, by default, JUnit 5 reporting prints the test methods
name in the IDE test report and also while executing test cases. We can use
@DisplayName annotation to provide a custom name to Test methods, that
makes it easier to read. Thus, it acts as a metadata for our test methods.

@DisplayName annotation can take up string having the following things:-

1. It can take spaces between words.


2. It can take special characters.
3. It can take emojis as well.

Let’s look at a demo:-

package io.educative.junit5;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

@DisplayName("Test class to demonstrate @Display name")


public class DisplayNameDemo {

@Test
public void testWithoutDisplayName() {
System.out.println("test method got executed!!!");
}

@Test
@DisplayName("Custom test name containing spaces")
public void testWithDisplayNameContainingSpaces() {
System.out.println("test method got executed!!!");
}

@Test
@DisplayName("Custom test name containing special characters - !@#$%^&*()_+~`╯°□°)╯"
public void testWithDisplayNameContainingSpecialCharacters() {
System.out.println("test method got executed!!!");
}

@Test
@DisplayName("Custom test name containing emojis - 😱")
public void testWithDisplayNameContainingEmoji() {
System.out.println("test method got executed!!!");
}
}

@DisplayName demonstration

Instead of printing actual test class and test names in the JUnit tab and
reports, it prints string provided in @DisplayName annotation.

It actually provides a textual representation of what actually test class and


@Test method do.
DisplayName annotation in JUnit 5@
5@
‫ﻣﺷﺎرﻛﺔ‬ ‫اﻟﻣﺷﺎھدة ﻻﺣﻘًﺎ‬

@DisplayName annotation

In the next chapter, we will discuss about Dependency Injection in JUnit 5.


TestInfo parameter

This lesson demonstrates how to use dependency injection (TestInfo Parameter) in Constructor and Test methods.

WE'LL COVER THE FOLLOWING

• ParameterResolver
• TestInfo Parameter
• Code Explanation

ParameterResolver #
In previous JUnit versions, there was limited/no support to allow parameters
in test constructors or methods. One of the major changes in JUnit 5 Jupiter
was that both test constructors and test methods are now allowed to have
parameters. These parameters provide metadata to constructors and test
methods. Thus, allows for greater flexibility and enables Dependency
Injection for test methods and constructors.

In Junit 5, there is an interface in org.junit.jupiter.api.extension package by


name, ParameterResolver . This interface defines the API for test extensions
that wish to dynamically resolve parameters at runtime.

There are different types of ParameterResolver’s in Junit 5. Generally, if a test


constructor or a @Test , @BeforeEach , @AfterEach , @BeforeAll , @AfterAll or
@TestFactory method accepts a parameter, the parameter must be resolved at
runtime by a registered ParameterResolver .

Read more -
https://junit.org/junit5/docs/5.3.2/api/org/junit/jupiter/api/extension/package-
summary.html for org.junit.jupiter.api.extension

https://junit.org/junit5/docs/5.3.2/api/org/junit/jupiter/api/extension/Parameter
Resolver.html for ParameterResolver .
TestInfo Parameter #
TestInfoParameterResolver - It is a built-in ParameterResolver. If a method
parameter is of type TestInfo , it signifies that TestInfoParameterResolver will
supply an instance of TestInfo corresponding to the current test as the value
for the parameter.

The TestInfo as the parameter can then be used to retrieve information or


metadata about the current test, such as the test’s display name, the test class,
the test method, or associated tags. If @DisplayName annotation is used on test
methods then the custom name associated with test methods is retrieved or
else technical name, which is the actual name of the test class or test method.

The following demonstrates how to have TestInfo injected into a test


constructor, @Test and lifecycle methods:-

package io.educative.junit5;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;

@DisplayName("Testing Dependency Injection")


public class TestInfoParameterDemo {

@BeforeAll
public static void beforeAll(TestInfo testInfo) {
System.out.println("beforeAll() got executed with test info as - ");
System.out.println("Display name - " + testInfo.getDisplayName());
System.out.println("Test Class - " + testInfo.getTestClass());
System.out.println("Test Method - " + testInfo.getTestMethod());
System.out.println("*******************************************");
}

public TestInfoParameterDemo(TestInfo testInfo) {


System.out.println("Constructor got executed with test info as - ");
System.out.println("Display name - " + testInfo.getDisplayName());
System.out.println("Test Class - " + testInfo.getTestClass());
System.out.println("Test Method - " + testInfo.getTestMethod());
System.out.println("*******************************************");
}

@BeforeEach
public void beforeEach(TestInfo testInfo) {
System.out.println("beforeEach() got executed with test info as - ");
System.out.println("Display name - " + testInfo.getDisplayName());
System.out.println("Test Class - " + testInfo.getTestClass());
System.out.println("Test Method - " + testInfo.getTestMethod());
System.out.println("*******************************************");
}
@Test
@DisplayName("test method by name testOne")

public void testOne(TestInfo testInfo) {


System.out.println("testOne() got executed with test info as - ");
System.out.println("Display name - " + testInfo.getDisplayName());
System.out.println("Test Class - " + testInfo.getTestClass());
System.out.println("Test Method - " + testInfo.getTestMethod());
System.out.println("*******************************************");
}

Code Explanation #
The above output of the program demonstrates how TestInfo parameter can
be injected into test constructor and test methods.

It gives information to test methods and constructor about the test class and
test methods.

Here, you can see @BeforeAll annotated method and constructor. It prints
@DisplayName value of test class and also prints test class fully qualified name.
Similarly, TestInfo provides the same info in @AfterAll annotated method.

Since for every new @Test method a new instance of test class is created,
therefore in @BeforeEach , @AfterEach and @Test annotated method, it prints
@DisplayName value of test method and also prints test class fully qualified
name.

In the next chapter, we will be studying about JUnit 5 Assumptions.


What are Assumptions in JUnit 5 ?

This lesson describes Assumptions in JUnit 5 and its usage.

WE'LL COVER THE FOLLOWING

• Assumptions in JUnit 5

Assumptions in JUnit 5 #
Assumptions in JUnit 5 is a collection of utility methods that support
conditional test execution based on assumptions. In comparison to failed
assertions, failed assumptions do not result in a test failure; rather, a failed
assumption results in a test being aborted.

Assumptions are typically used whenever it does not make sense to continue
execution of a given test method — for example, if the test depends on
something that does not exist in the current runtime environment.

If the assumptions are not satisfied then, TestAbortedException is thrown.

There are 3 types of Assumptions in Junit 5:

assumeTrue

assumeFalse

assumingThat

In the upcoming lesson, let’s look into each Assumptions in detail.


assumeTrue() and assumeFalse() method

This lesson demonstrates how to use assumeTrue and assumeFalse methods in JUnit 5 to make conditional
assumptions.

WE'LL COVER THE FOLLOWING

• assumeTrue()
• Demo
• assumeFalse()
• Demo

assumeTrue() #
Assumptions API in JUnit 5 has a static utility method called as, assumeTrue() .
It validates the given assumption to true.

if the assumption is true then test proceeds to execution.


if the assumption is false then test execution is aborted.

There are basically three useful overloaded methods for assumeTrue.

// boolean assumption to validate


public static void assumeTrue(boolean assumption) throws TestAbortedException
public static void assumeTrue(boolean assumption, Supplier<String> messageSupplier) throws Te
public static void assumeTrue(boolean assumption, String message) throws TestAbortedException

// BooleanSupplier to provide boolean assumption to validate


public static void assumeTrue(BooleanSupplier assumptionSupplier) throws TestAbortedException
public static void assumeTrue(BooleanSupplier assumptionSupplier, String message) throws Test
public static void assumeTrue(BooleanSupplier assumptionSupplier, Supplier<String> messageSup

Demo #
Let’s look into the usage of the above methods.

package io.educative.junit5;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import org.junit.jupiter.api.Test;

public class AssumeTrueDemo {

@Test
void testOnDevelopmentEnvironment() {
System.setProperty("ENV", "DEV");
assumeTrue("DEV".equals(System.getProperty("ENV")));
//remainder of test will proceed
}

@Test
void testOnProductionEnvironment() {
System.setProperty("ENV", "PROD");
assumeTrue("DEV".equals(System.getProperty("ENV")), "Assumption failed");
// remainder of test will be aborted
}
}

assumeFalse() #
Assumptions API in JUnit 5 has a static utility method called as assumeFalse() .
It validates the given assumption to false.

if the assumption is false then test proceeds to execution.


if the assumption is true then test execution is aborted.

There are basically three useful overloaded methods for assumeFalse.

// boolean assumption to validate


public static void assumeFalse(boolean assumption) throws TestAbortedException
public static void assumeFalse(boolean assumption, Supplier<String> messageSupplier) throws T
public static void assumeFalse(boolean assumption, String message) throws TestAbortedExceptio
// BooleanSupplier to provide boolean assumption to validate
public static void assumeFalse(BooleanSupplier assumptionSupplier) throws TestAbortedExceptio

public static void assumeFalse(BooleanSupplier assumptionSupplier, String message) throws Tes


public static void assumeFalse(BooleanSupplier assumptionSupplier, Supplier<String> messageSu

Demo #
Let’s look into the usage of the above methods.

package io.educative.junit5;

import static org.junit.jupiter.api.Assumptions.assumeFalse;

import org.junit.jupiter.api.Test;

public class AssumeFalseDemo {

@Test
void testOnDevelopmentEnvironment() {
System.setProperty("ENV", "DEV");
assumeFalse("DEV".equals(System.getProperty("ENV")), "Assumption failed");
//remainder of test will be aborted
}

@Test
void testOnProductionEnvironment() {
System.setProperty("ENV", "PROD");
assumeFalse("DEV".equals(System.getProperty("ENV")));
// remainder of test will proceed
}
}

In the next lesson we will learn about assumingThat() method.


assumingThat() method

This lesson demonstrates how to use the assumingThat method in JUnit 5 to make conditional assumptions.

WE'LL COVER THE FOLLOWING

• assumingThat()
• Demo

assumingThat() #
Assumptions API in JUnit 5 has a static utility method called, assumingThat() .
This method takes a boolean assumption and an Executable. It validates the
given assumption and based on its outcome it decides whether to execute an
Executable or not.

If the assumption is invalid, this method does nothing.


If the supplied assumption is valid, it executes the supplied Executable.

There are basically two useful overloaded methods for assumingThat.

public static void assumingThat(boolean assumption, Executable executable)


public static void assumingThat(BooleanSupplier assumptionSupplier, Executable executable)

Demo #
Let’s look into the usage of the above methods.

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertEquals;


import static org.junit.jupiter.api.Assumptions.assumingThat;

import org.junit.jupiter.api.Test;

public class AssumingThatDemo {

@Test
void testInAllEnvironments() {
System.setProperty("ENV", "DEV");
assumingThat("DEV".equals(System.getProperty("ENV")),

() -> {
// perform these assertions only on the Dev server
System.out.println("Perform these assertions only on the Dev server !!!");
assertEquals(2, 1 + 1);
});

// perform these assertions in all environments


assertEquals(42, 40 + 2);
}

@Test
void testInAllEnvironments2() {
System.setProperty("ENV", "DEV");
assumingThat("PROD".equals(System.getProperty("ENV")),
() -> {
// perform these assertions only on the Prod server
System.out.println("Perform these assertions only on the Prod server !!!");
assertEquals(2, 1 + 1);
});

// perform these assertions in all environments


assertEquals(42, 40 + 2);
}
}

In the next chapter we will learn about Disable or Enable Tests in JUnit 5.
Disable Test Method and Class - @Disabled

This lesson demonstrates how to disable the test method or a complete test class.

WE'LL COVER THE FOLLOWING

• @Disabled annotation
• @Disabled annotation on Test class
• @Disabled annotation on @Test method

@Disabled annotation #
There are many ways to enable or disable test methods or test class in Junit 5.
@Disabled annotation if applied to the test class, then all the tests present in
the class gets disabled and if applied on the test method, then that test method
is not executed. @Disabled annotation also takes one optional parameter,
which provides a reason for disabling test case for documentation.

@Disabled annotation on Test class #


Applying @Disabled annotation on test class will make test class and all test
methods within that class disabled.

Let’s look at a demo.

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertFalse;


import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

@Disabled
public class DisabledClassTest {

@Test
void testMethod1() {
assertTrue(4 > 0);
}

@Test

void testMethod2() {
assertFalse(4 < 0);
}
}

Here, @Disabled annotation is placed on test class DisabledClassTest . On


running above test class it shows that test case is passed, but it also shows that
2/2 (2 skipped). Thus, providing @Disabled annotation on test class will make
all of its test methods as disabled.

@Disabled annotation on @Test method #


Applying @Disabled annotation on the test method will make the test method
disabled. It will be skipped from execution.

Let’s look at a demo.

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

public class DisabledMethodTest {

@Test
void testOnDevelopmentEnvironment() {
System.setProperty("ENV", "DEV");
assertTrue("DEV".equals(System.getProperty("ENV")));
}

@Disabled("Skip in upper environments")


@Test
void testOnProductionEnvironment() {
System.setProperty("ENV", "PROD");
assertTrue("PROD".equals(System.getProperty("ENV")));
}
}

Here, @Disabled annotation is placed on the @Test method


testOnDevelopmentEnvironment() . On running above test class it shows that test
cases are passed, but it also shows that 2/2 (1 skipped). Thus, providing
@Disabled annotation on the test method will make it disabled i.e. it will be
skipped from getting executed.

In the next lesson we will learn about DisabledOnOs and EnableOnOs .


Operating System Conditions - @DisabledOnOs and
@EnabledOnOs

This lesson demonstrates how to disable or enable the test method or a complete test class using OS-level
conditions.

WE'LL COVER THE FOLLOWING

• @DisabledOnOs and @EnabledOnOs

@DisabledOnOs and @EnabledOnOs #


Junit 5 helps us to disable or enable test cases using various conditions. JUnit
Jupiter API provides annotations in org.junit.jupiter.api.condition -
https://junit.org/junit5/docs/5.3.2/api/org/junit/jupiter/api/condition/package-
summary.html

package to enable/disable tests based on a certain condition. The annotations


provided by API can be applied to test methods as well as the class itself. The
two annotations which are applied to disable/enable tests based on Operating
system are - @DisabledOnOs and @EnabledOnOs . Let’s take a look at a demo.

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertFalse;


import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;

public class DisabledOnOsTest {

@Test
void testOnAllOs() {
assertTrue(3 > 0);
}

@DisabledOnOs(OS.MAC)
@Test
void testDisableOnMacOs() {
assertFalse(0 > 4);
}

@DisabledOnOs(OS.WINDOWS)
@Test
void testDisableOnWindowOs() {
assertFalse(10 > 40);
}
}

Above test program has 3 test methods and @DisabledOnOs is applied on 2 test
methods as -

1. testDisableOnMacOs() - Here, @DisabledOnOs annotation takes in value as -


OS.MAC . It makes the test method skip to execute on Mac operating
system. It will not skip on other operating systems.
2. testDisableOnWindowOs() - Here, @DisabledOnOs annotation takes in value
as - OS.WINDOWS . It makes the test method skip to execute on Windows
operating system. It will not skip on other operating systems.

The above test methods are executed on the Mac operating system. Thus, the
output shows that 1 test method marked as, @DisabledOnOs(OS.MAC) is skipped
for execution.

EnabledOnOsTest.java

package com.hubberspot.junit5.disabled;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;

public class EnabledOnOsTest {

@Test
void testOnAllOs() {
assertTrue(3 > 0);
}

@EnabledOnOs(OS.WINDOWS)
@Test
void testEnabledOnWindowsOs() {
assertFalse(0 > 4);
}

@EnabledOnOs(OS.MAC)
@Test
void testEnabledOnMacOs() {
assertFalse(10 > 40);
}
}

Output of tests

Above test program has 3 test methods and @EnabledOnOs annotation is


applied on 2 test methods as -

1. testEnabledOnWindowsOs() - Here, @EnabledOnOs annotation takes in value


as - OS.WINDOWS . It makes the test method enabled to execute only on the
Windows operating system. It will get skipped on other operating
systems.
2. testEnabledOnMacOs() - Here, @EnabledOnOs annotation takes in value as -
OS.MAC . It makes the test method enabled to execute only on Mac
operating system. It will get skipped on other operating systems.

The above test methods are executed on the Mac operating system. Thus, the
output shows that 1 test method marked as, @EnabledOnOs(OS.WINDOWS) is
skipped for execution. It will execute when tests are run on Windows
operating system.

In the next lesson we will learn about DisabledOnJre and EnableOnJre based
conditions.
Java Runtime Environment Conditions -
@DisabledOnJre and @EnabledOnJre

This lesson demonstrates how to disable or enable test methods or a complete test class using JRE level
conditions.

WE'LL COVER THE FOLLOWING

• @DisabledOnJre and @EnabledOnJre

@DisabledOnJre and @EnabledOnJre #


Junit 5 helps us to disable or enable test cases using various conditions. JUnit
Jupiter API provides annotations in org.junit.jupiter.api.condition package
to enable/disable tests based on a certain condition. The annotations provided
by API can be applied to test methods as well as the class itself. The two
annotations which are applied to disable/enable tests based on the particular
version of the Java Runtime Environment (JRE) are - @DisabledOnJre and
@EnabledOnJre . Let’s take a look at a demo.

DisabledOnJreTest.java

package com.hubberspot.junit5.disabled;

import static org.junit.jupiter.api.Assertions.assertFalse;


import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;

public class DisabledOnJreTest {

@Test
void testOnAllJre() {
assertTrue(3 > 0);
}

@DisabledOnJre(JRE.JAVA_8)
@Test
void testDisableOnJava8() {
assertFalse(0 > 4);
}

@DisabledOnJre(JRE.JAVA_9)
@Test
void testDisableOnJava9() {
assertFalse(10 > 40);
}
}

Above test program has 3 test methods and @DisabledOnJre is applied on 2 test
methods as.

1. testDisableOnJava8() - Here, @DisabledOnJre annotation takes in value as


- JRE.JAVA_8 . It makes the test method skip to execute on Java 8 runtime
environment. It will not skip on other Java runtime environments.
2. testDisableOnJava9() - Here, @DisabledOnJre annotation takes in value as
- JRE.JAVA_9 . It makes the test method skip to execute on Java 9 runtime
environment. It will not skip on other Java runtime environments.

The above test methods are executed on the Java 8 runtime environment.
Thus, the output shows that 1 test method marked as,
@DisabledOnJre(JRE.JAVA_8) is skipped for execution.

EnabledOnJreTest.java

package com.hubberspot.junit5.disabled;

import static org.junit.jupiter.api.Assertions.assertFalse;


import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnJre;
import org.junit.jupiter.api.condition.JRE;

public class EnabledOnJreTest {

@Test
void testOnAllJre() {
assertTrue(3 > 0);
}

@EnabledOnJre(JRE.JAVA_8)
@Test
void testEnabledOnJava8() {
assertFalse(0 > 4);
}

@EnabledOnJre(JRE.JAVA_9)
@Test
void testEnabledOnJava9() {
assertFalse(10 > 40);
}
}

Output of tests

Above test program has 3 test methods and @EnabledOnJre annotation is


applied on 2 test methods as.

1. testEnabledOnJava8() - Here, @EnabledOnJre annotation takes in value as -


JRE.JAVA_8 . It makes the test method enabled to execute only on Java 8
runtime environment. It will get skipped on other Java runtime
environments.
2. testEnabledOnJava9() - Here, @EnabledOnJre annotation takes in value as -
JRE.JAVA_8 . It makes the test method enabled to execute only on Java 9
runtime environment. It will get skipped on other Java runtime
environments.

The above test methods are executed on Java 8 runtime environment. Thus,
the output shows that 1 test method marked as, @EnabledOnJre(JRE.JAVA_9) is
skipped for execution. It will execute when tests are run on Java 9 runtime
environment.
System Property Conditions -
@DisabledIfSystemProperty and
@EnabledIfSystemProperty

This lesson demonstrates how to disable or enable test methods or a complete test class using System property
level conditions.

WE'LL COVER THE FOLLOWING

• @DisabledIfSystemProperty and @EnabledIfSystemProperty

@DisabledIfSystemProperty and @EnabledIfSystemProperty


#
Junit 5 helps us to disable or enable test cases using various conditions. JUnit
Jupiter API provides annotations in org.junit.jupiter.api.condition package
to enable/disable tests based on a certain condition. The annotations provided
by API can be applied to test methods as well as the class itself. The two
annotations which use system properties and specified regex to disable or
enable tests are - @DisabledIfSystemProperty and @EnabledIfSystemProperty .
Let’s take a look at a demo.

DisabledIfSystemPropertyTest.java

package com.hubberspot.junit5.disabled;

import static org.junit.jupiter.api.Assertions.assertFalse;


import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;

public class DisabledIfSystemPropertyTest {

@Test
void testOnAllSystemProperties() {
assertTrue(3 > 0);
}
@DisabledIfSystemProperty(named="user.name", matches="dinesh")
@Test
void testDisabledIfUserNameMatchesDinesh() {
assertFalse(0 > 4);
}

@DisabledIfSystemProperty(named="os.name", matches="Windows")
@Test
void testDisabledIfOperatingSystemMatchesWindows() {
assertFalse(10 > 40);
}
}

Above test program has 3 test methods and @DisabledIfSystemProperty is


applied on 2 test methods as.

1. testDisabledIfUserNameMatchesDinesh() - Here,
@DisabledIfSystemProperty annotation takes in two attributes such as
named and matches . The value provided to named attribute is "user.name"
and value provided to matches attribute is "dinesh" . It makes the test
method skip to execute if System property by name "user.name" matches
"dinesh" .

2. testDisabledIfOperatingSystemMatchesWindows() - Here,
@DisabledIfSystemProperty annotation takes in two attributes such as
named and matches . The value provided to named attribute is "os.name"
and value provided to matches attribute is "Windows" . It makes the test
method skip to execute if System property by name "os.name" matches
"Windows" .

The above test methods are executed on System properties as -


1. user.name - dinesh
2. os.name - Mac OS X
Thus, output shows that 1 test method marked as,
@DisabledIfSystemProperty(named="user.name", matches="dinesh") is skipped
for execution.

EnabledIfSystemPropertyTest.java

package com.hubberspot.junit5.disabled;

import static org.junit.jupiter.api.Assertions.assertFalse;


import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;

public class EnabledIfSystemPropertyTest {

@Test
void testOnAllSystemProperties() {
assertTrue(3 > 0);
}

@EnabledIfSystemProperty(named="user.name", matches="dinesh")
@Test
void testEnabledIfUserNameMatchesDinesh() {
assertFalse(0 > 4);
}

@EnabledIfSystemProperty(named="os.name", matches="Windows")
@Test
void testEnabledIfOperatingSystemMatchesWindows() {
assertFalse(10 > 40);
}
}

Output of tests
Above test program has 3 test methods and @EnabledIfSystemProperty is
applied on 2 test methods as -

1. testEnabledIfUserNameMatchesDinesh() - Here, @EnabledIfSystemProperty


annotation takes in two attributes such as named and matches . The value
provided to named attribute is "user.name" and value provided to
matches attribute is "dinesh" . It makes the test method enable to execute
if System property by name "user.name" matches "dinesh" .

2. testEnabledIfOperatingSystemMatchesWindows() - Here,
@EnabledIfSystemProperty annotation takes in two attributes such as
named and matches . The value provided to named attribute is "os.name"
and value provided to matches attribute is "Windows" . It makes the test
method enable to execute if System property by name "os.name" matches
"Windows" .

The above test methods are executed on System properties as -

1. user.name - dinesh
2. os.name - Mac OS X

Thus, output shows that 1 test method marked as,


@EnabledIfSystemProperty(named="os.name", matches="Windows") is skipped for
execution.
Environment Variable Conditions -
@DisabledIfEnvironmentVariable and
@EnabledIfEnvironmentVariable

This lesson demonstrates how to disable or enable test methods or a complete test class using Environment
variable conditions.

WE'LL COVER THE FOLLOWING

• @DisabledIfEnvironmentVariable and @EnabledIfEnvironmentVariable

@DisabledIfEnvironmentVariable and
@EnabledIfEnvironmentVariable #
Junit 5 helps us to disable or enable test cases using various conditions. JUnit
Jupiter API provides annotations in org.junit.jupiter.api.condition package
to enable/disable tests based on a certain condition. The annotations provided
by API can be applied to test methods as well as the class itself. The two
annotations which use system environment properties and specified regex to
disable or enable tests are - @DisabledIfEnvironmentVariable and
@EnabledIfEnvironmentVariable . Let’s take a look at a demo.

DisabledIfEnvironmentVariableTest.java

package com.hubberspot.junit5.disabled;

import static org.junit.jupiter.api.Assertions.assertFalse;


import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable;

public class DisabledIfEnvironmentVariableTest {

@Test
void testOnAllEnvironmentVariables() {
assertTrue(3 > 0);
}
@DisabledIfEnvironmentVariable(named="USER", matches="dinesh")
@Test
void testDisabledIfUserMatchesDinesh() {
assertFalse(0 > 4);
}

@DisabledIfEnvironmentVariable(named="HOME", matches="/dummies/home")
@Test
void testDisabledIfHomeMatchesDummyDirectory() {
assertFalse(10 > 40);
}
}

Above test program has 3 test methods and @DisabledIfEnvironmentVariable is


applied on 2 test methods as.

1. testDisabledIfUserMatchesDinesh() - Here,
@DisabledIfEnvironmentVariable annotation takes in two attributes such
as named and matches . The value provided to named attribute is "USER"
and value provided to matches attribute is "dinesh" . It makes the test
method skip to execute if environment variable by name “USER” matches
“dinesh”.
2. testDisabledIfHomeMatchesDummyDirectory() - Here,
@DisabledIfEnvironmentVariable annotation takes in two attributes such
as named and matches . The value provided to named attribute is "HOME"
and value provided to matches attribute is "/dummies/home" . It makes the
test method skip to execute if environment variable by name "HOME"
matches "/dummies/home" .

The above test methods are executed on environment variables as -


1. USER - dinesh
2. HOME - /Users/dinesh

Thus, output shows that 1 test method marked as,


@DisabledIfEnvironmentVariable(named="USER", matches="dinesh") is skipped
for execution.

EnabledIfEnvironmentVariableTest.java

package com.hubberspot.junit5.disabled;

import static org.junit.jupiter.api.Assertions.assertFalse;


import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;

public class EnabledIfEnvironmentVariableTest {

@Test
void testOnAllEnvironmentVariables() {
assertTrue(3 > 0);
}

@EnabledIfEnvironmentVariable(named="USER", matches="dinesh")
@Test
void testEnabledIfUserMatchesDinesh() {
assertFalse(0 > 4);
}

@EnabledIfEnvironmentVariable(named="HOME", matches="/dummies/home")
@Test
void testEnabledIfHomeMatchesDummyDirectory() {
assertFalse(10 > 40);
}
}

Output of tests
Above test program has 3 test methods and @EnabledIfEnvironmentVariable is
applied on 2 test methods as -

1. testEnabledIfUserMatchesDinesh() - Here, @EnabledIfEnvironmentVariable


annotation takes in two attributes such as named and matches . The value
provided to named attribute is "USER" and value provided to matches
attribute is "dinesh" . It makes the test method enable to execute if
environment variable by name "USER" matches "dinesh" .
2. testEnabledIfHomeMatchesDummyDirectory() - Here,
@EnabledIfEnvironmentVariable annotation takes in two attributes such as
named and matches . The value provided to named attribute is "HOME" and
value provided to matches attribute is "/dummies/home" . It makes the test
method enable to execute if environment variable by name "HOME"
matches "/dummies/home" .

The above test methods are executed on environment variables as -

1. USER - dinesh
2. HOME - /Users/dinesh

Thus, output shows that 1 test method marked as,


@EnabledIfEnvironmentVariable(named="HOME", matches="/dummies/home") is
skipped for execution.

In the next chapter, we will discuss about @Nested annotation.


@Nested Tests

This lesson demonstrates how to use @Nested annotation to con gure the test hierarchy.

WE'LL COVER THE FOLLOWING

• @Nested Tests
• Explanation

@Nested Tests #
@Nested annotation provides tests creator more functionality to show the
relationship among several groups of tests.

This relationship is achieved by providing nested classes to the main test class.
But, by default nested classes don’t participate in test execution. In order to
provide testing capabilities to nested classes @Nested annotation is used.

Let’s take a look at a demo.

package io.educative.junit5;

import static org.junit.Assert.assertNull;


import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.LinkedList;
import java.util.Queue;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

@DisplayName("A queue")
public class TestingAQueueDemo {
Queue<String> queue; // A Queue of String

@Test
@DisplayName("is null")
void isNotInstantiated() {
assertNull(queue);
}

@Nested
@DisplayName("when new")
class WhenNew {

@BeforeEach
void createNewStack() {
queue = new LinkedList<>();
}

@Test
@DisplayName("is empty")
void isEmpty() {
assertTrue(queue.isEmpty());
}

@Test
@DisplayName("return null element when polled")
void returnNullWhenPolled() {
assertNull(queue.poll());
}

@Test
@DisplayName("return null element when peeked")
void returnNullWhenPeeked() {
assertNull(queue.peek());
}

@Nested
@DisplayName("after offering an element")
class AfterOffering {

String anElement = "an element";

@BeforeEach
void offerAnElement() {
queue.offer(anElement);
}

@Test
@DisplayName("it is no longer empty")
void isNotEmpty() {
assertFalse(queue.isEmpty());
}

@Test
@DisplayName("returns the element when polled and is empty")
void returnElementWhenPolled() {
assertEquals(anElement, queue.poll());
assertTrue(queue.isEmpty());
}

@Test
@DisplayName("returns the element when peeked but remains not empty")
void returnElementWhenPeeked() {
assertEquals(anElement, queue.peek());
assertFalse(queue.isEmpty());
}
}
}
}

Explanation #
On running TestingAQueueDemo.java as JUnit Test case, the output generated is
demonstrated in the above image.

@Nested annotation helps us writing test cases in a more descriptive way.


Nested classes enforce the idea of Behaviour Driven Development. It separates
our test class in logical groupings. It helps us in readability of test cases.

In the next chapter, we will discuss about JUnit 5 Integration with Maven.
Create a maven project in Eclipse

This lesson demonstrates steps to integrate JUnit 5 with Maven.

WE'LL COVER THE FOLLOWING

• What is Maven?
• Create Maven Project in Eclipse

What is Maven? #
As per Wikipedia - Maven is a build automation tool used primarily for Java
projects. Maven addresses two aspects of building software:

1. It describes how software is built.

2. It describes its dependencies.

It uses an XML file, also called as pom.xml. This XML file describes the
software project being built, its dependencies on other external modules and
components, the build order, directories, and required plug-ins.

Create Maven Project in Eclipse #


Let’s see step by step demonstration to create a Maven project in Eclipse IDE.

Step 1 - Launch Eclipse IDE.

Step 2 - Create a new Maven Project. Right click on File --> New --> Project as
demonstrated in the figure below.
A New Project wizard will be opened. It will show various projects eclipse can
create.

Step 3 - Search for "Maven" in New Project Wizard.

Step 4 - Select Maven Project and Click on Next, as demonstrated in the


figure below.
Step 5 - Select "Create a Simple project (skip archetype selection)" and
Click on Next, as demonstrated in the figure below.
Step 6 - Enter Group Id, Artifact Id and Version of your preference or as
demonstrated in the figure below.

Step 7 - Click on Finish.

A new Maven project by name, junit5-maven-starter is created in Eclipse


IDE.
JUnit 5 Dependencies

This lesson explains dependencies required to create and run Junit 5 Test cases in Maven.

WE'LL COVER THE FOLLOWING

• Maven Dependencies

Maven Dependencies #
Now, that our Java Maven project is created, we have to make a couple of
changes in the pom.xml file. Expand junit5-maven-starter project and open
the pom.xml file in IDE. Apply the changes as provided in below XML:-

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchem


<modelVersion>4.0.0</modelVersion>
<groupId>com.hubberspot</groupId>
<artifactId>junit5-maven-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>${maven.compiler.source}</maven.compiler.target>

<junit.jupiter.version>5.3.2</junit.jupiter.version>
</properties>

<dependencies>

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
</depe de cy>

</dependencies>

<build>
<plugins>
<!-- JUnit 5 requires Surefire version 2.22.1 or higher -->
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
</plugins>
</build>

</project>

In order to kick start Junit 5 in Maven, following three dependencies/plugins


are required -

1. junit-jupiter-api - This dependency is required because it defines the API


that we need to write Junit 5 tests.

2. junit-jupiter-engine - This dependency is required because it is the


implementation of the junit-platform-engine API for JUnit 5. It is responsible
for the discovery and execution of Junit 5 tests.

3. maven-surefire-plugin - This plugin is required because it is needed for


tests to be executed during the maven build.

It also requires Java 8 or higher versions.

There are few more dependencies required to run JUnit 4 test cases along with
Junit 5, also writing parameterized tests etc. We will discuss more on this in
the respective lesson.
Create and run JUnit 5 Test Case

This lessons focuses on creating and running JUnit 5 test cases in Maven.

WE'LL COVER THE FOLLOWING

• Create a Java class


• Create method inside Calculator class
• Create a Java Test class
• Add a @Test method

Create a Java class #


After adding the required dependencies, let’s create a Java class. It will be our
class under test.

Step 1 - Expand the junit5-maven-starter project. In order to create a new


Java class, right-click on src/main/java traverse to New --> Class. Click on
Class to add a new Java class.

Step 2 - New Java Class popup window will be opened.

Step 3 - Provide Package name of your choice.

Step 4 - Enter Name of class as, Calculator.

Step 5 - Click Finish.

A Java class by name Calculator.java will be created in Eclipse IDE. See the
demonstration of steps below.
Create method inside Calculator class #
Step 1 - Create a method by name, addition() into Calculator class. For this
method, we will write and execute JUnit 5 test cases in Maven.

Step 2 - addition() takes in two integer arguments say, num1 and num2.

Step 3 - It will calculate the sum of num1 and num2 and will return it.

See the demonstration of steps below.

Calculator.java

package com.hubberspot.junit5;

public class Calculator {


public int addition(int num1, int num2) {
return num1 + num2;
}
}
Create a Java Test class #
Let’s create a Java Test class. It will test Calculator.java class.

Step 1 - Expand the junit5-maven-starter project. In order to create a new


Java Test class, right-click on src/test/java traverse to New --> Class. Click on
Class to add a new Java class.

Note -The test class will be created in src/test/java, as it will allow


seperation of concerns, i.e. keeping source files seperate from the test
files.

Step 2 - New Java Class popup window will be opened.

Step 3 - As a best practice, we keep the same Package name of the test class
and src class. Thus, folder names are different but package names are same.

Step 4 - As it is a test class and it provides test methods for Calculator class
therefore, we keep Name of class as, CalculatorTest.
Step 5 - Click Finish.

A Java class by name CalculatorTest.java will be created in Eclipse IDE. See


demonstration of steps below.

Add a @Test method #


In CalculatorTest.java class create a test method
givenTwoNumbers3And4_whenAdditionIsCalled_then7IsReturned(). This
method is created using given/when/then format, which we will discuss more
in upcoming lessons. This method is marked with @Test annotation, which
signifies that it is a test method. This method tests addition of two numbers by
calling addition() method of Calculator class.

It passes two numbers as, 3 and 4 and expects 7 to be returned from


addition() method. It asserts return value using assertEquals() method
present in Assertions API, which we will discuss more in upcoming lessons.

On running mvn test command. It executes @Test method using Maven.

CalculatorTest.java
package com.hubberspot.junit5;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

public class CalculatorTest {

@Test
public void givenTwoNumbers3And4_whenAdditionIsCalled_then7IsReturned() {
Calculator calculator = new Calculator();
assertEquals(7, calculator.addition(3, 4));
}

}
Parameterized Tests Setup

This lesson demonstrates how to setup and run Parameterized Tests in JUnit 5.

WE'LL COVER THE FOLLOWING

• Introduction to Parameterized Tests


• Setup

Introduction to Parameterized Tests #


Parameterized tests allow us to run a test multiple times with different
arguments. Parameterized tests are normal test methods but instead of
annotating them with @Test , we use @ParameterizedTest annotation.

In order to pass different arguments to @ParameterizedTest annotated


method, we need to provide a source .

A source is simply a collection of different arguments.

JUnit 5 has many types or ways through which we pass different arguments to
test methods.

Setup #
Maven - In order to use parameterized tests, you need to add a dependency for
junit-jupiter-params to maven project. Just add below dependency to
pom.xml which we created in our earlier lesson (Junit 5 Integration with
Maven) -
https://www.educative.io/collection/page/4753235730497536/569341723751219
2/5071437253574656.

pom.xml
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>

junit-jupiter-params maven dependency

In our upcoming lesson, we will learn how to use multiple sources to pass
different arguments to @ParameterizedTest methods.
Parameterized Test with @ValueSource

This lesson demonstrates use of @ValueSource to pass different arguments to @ParameterizedTest.

WE'LL COVER THE FOLLOWING

• @ValueSource

@ValueSource #
@ValueSource is one of the simplest ways to pass arguments array to
@ParameterizedTest method. This array can be of following types -

1. short
2. byte
3. int
4. long
5. float
6. double
7. char
8. java.lang.String
9. java.lang.Class

Let’s look into a demo.

Step 1 - Let’s create a class OddEven.java , it is our class under test.

Step 2 - To this class we provide a method by name isNumberEven() . This


method takes in an integer value and returns true if the number is even or
false if the number is odd.

OddEven.java

package com.hubberspot.junit5.parameterized;
public class OddEven {

public boolean isNumberEven(int number) {


return number % 2 == 0;
}

Step 3 - We create a test class by name, OddEvenTest.java .

Step 4 - It contains a test method by name,


givenANumber_whenIsEvenIsCalled_thenTrueIsReturnedForEvenNumbers . In order
to provide different parameters/values to the same test method, this method is
marked as @ParameterizedTest instead of @Test . @ParameterizedTest
annotation makes this test method eligible to take multiple values from
different sources.

Step 5 - In order to provide different and multiple values through


@ValueSource we mark this test method with @ValueSource annotation. This
annotation takes arguments in the form of an array.

Step 6 - Let’s pass integer array with different values such as 2,4,6,8,
Integer.MAX_VALUE. There are 5 integer values so @ParameterizedTest will
execute 5 times. In each iteration, it will assert one integer value to check
whether it is even or not. Thus, saving a lot of time spent writing the same
tests for different values again and again.

Step 7 - Run it as, JUnit Test Case.

OddEven.java

OddEvenTest.java

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

class OddEvenTest {

@ParameterizedTest
@ValueSource(ints = {2,4,6,8,Integer.MAX_VALUE})
void givenANumber_whenIsEvenIsCalled_thenTrueIsReturnedForEvenNumbers(int number) {
OddEven oddEven = new OddEven();
assertTrue(oddEven.isNumberEven(number));
}

Output of @ParameterizedTest demo

Above image demonstrates the working of @ParameterizedTest . As we have


provided 5 different values, the test case ran 5 times. As 2,4,6,8 are even
numbered so respective test cases pass, but Integer.MAX_VALUE(2147483647)
is odd thus, last test case fail.

In the next lesson we will be studying parameterized tests with @Enumsource


ParameterizedTest with @EnumSource

This lesson demonstrates use of @EnumSource to pass different arguments to @ParameterizedTest.

WE'LL COVER THE FOLLOWING

• @EnumSource

@EnumSource #
@EnumSource allows us to pass enum constants to @ParameterizedTest method.

Let’s look at a demo.

Step 1 - Let’s assume that we have to write a parameterized test that takes a
value of the Animal enum as @EnumSource . The Pet enum looks as follows.

Animal.java

package com.hubberspot.junit5.parameterized;

public enum Animal {


ELEPHANT,
TIGER,
DOG,
CAT,
MOUSE
}

Step 3 - We create a test class by name, EnumSourceTest.java .

Step 4 - It contains a test method by name, testEnumSource . In order to


provide different parameters/values to the same test method, this method is
marked as @ParameterizedTest instead of @Test .

Step 5 - In order to provide different and multiple values through enums. We


mark this test method with @EnumSource annotation. This annotation takes
Animal.class instance.
Step 6 - Let’s pass Animal enum type to test method. There are 5 animal such
as ELEPHANT, TIGER, DOG, CAT, MOUSE, so @ParameterizedTest will execute 5
times. In each iteration, it will assert one enum value that it’s not null.

Step 7 - Run it as, JUnit Test Case.

package io.educative.junit5;
Animal.java
import static org.junit.jupiter.api.Assertions.*;
EnumSourceTest.java
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;

class EnumSourceTest {

@ParameterizedTest
@EnumSource(Animal.class)
void testEnumSource(Animal animal) {
assertNotNull(animal);
}

Output of @ParameterizedTest demo

Above image demonstrates the working of @ParameterizedTest . As we have


provided 5 different enum values, the test case ran 5 times. As all enum values
are not null, therefore assertNotNull passes for all values passed.
In the next lesson we will be studying parameterized tests with
@MethodSource .
ParameterizedTest with @MethodSource

This lesson demonstrates use of @MethodSource to pass different arguments to @ParameterizedTest.

WE'LL COVER THE FOLLOWING

• @MethodSource

@MethodSource #
@MethodSource allows us to specify a factory method for different test
arguments. This factory method must be static and can be present in the
same class or any other class too. The factory method should return Stream,
Iterator, Iterable or array of elements to @ParameterizedTest method.

Let’s look at a demo.

Step 1 - Let’s assume that we have to write a parameterized test that takes
values of the static factory method as @MethodSource .

Step 2 - We create a test class by name, MethodSourceTest.java .

Step 3 - It contains a test method by name, testMethodSource . In order to


provide different parameters/values to the same test method, this method is
marked as @ParameterizedTest instead of @Test .

Step 4 - In order to provide different and multiple values through factory


methods. We mark this test method with @MethodSource annotation. This
annotation takes in name of factory method which will provide streams/lists
of data to @ParameterizedTest .

Let’s see the test class below.

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.*;


import java.util.stream.Stream;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

class MethodSourceTest {

@ParameterizedTest
@MethodSource("parameterProvider")
void testWithSimpleMethodSource(String argument) {
assertNotNull(argument);
}

// method name is the source to test


static Stream<String> parameterProvider() {
return Stream.of("parameter1", "parameter2");
}

Output of @ParameterizedTest demo

Above image demonstrates the working of @ParameterizedTest . As we have


provided two different method source values by providing a static method
as parameterProvider() , whose return type is Streams of String, therefore, the
test case ran 2 times. We provide a static method name to @MethodSource
annotation, which internally calls method parameterProvider() to get
different parameters values. Also, all string values provided by
parameterProvider() method are not null therefore assertNotNull passes for
all values passed.
In the next lesson we will be studying parameterized tests with @CsvSource .
ParameterizedTest with @CsvSource

This lesson demonstrates the use of @CsvSource to pass different arguments to @ParameterizedTest.

WE'LL COVER THE FOLLOWING

• @CsvSource

@CsvSource #
@CsvSource allows you to provide parameter lists as comma-separated
custom-delimiter separated values. @CsvSource annotation uses single quote
along with comma-separated delimiter to distinguish a csv value from others.

For e.g -

{“one, two”} will result to 2 arguments as - “one”, “two”.


{“one, ‘two, three’”} will result to 2 arguments as - “one”, “two, three”.
{“one, ‘’”} will result to 2 arguments as - “one”, “”.
{"one, "} will result to 2 arguments as - “one”, null.

Let’s look at a demo.

Step 1 - Let’s assume that we have to write a parameterized test that takes
values from @CsvSource .

Step 2 - We create a test class by name, CsvSourceTest.java .

Step 3 - It contains a test method by name, testCsvSource . In order to provide


different parameters/values to the same test method, this method is marked as
@ParameterizedTest instead of @Test .

Step 4 - In order to provide different and multiple values through csv source.
We mark this test method with @CsvSource annotation. This annotation takes
comma-separated values which will provide streams/lists of data to
@ParameterizedTest .

Let’s see the test class below.

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class CsvSourceTest {

@ParameterizedTest
@CsvSource({ "one, 1", "two, 2", "'foo, bar', 3" })
void testWithCsvSource(String first, int second) {
assertNotNull(first);
assertNotEquals(0, second);
}

Output of @ParameterizedTest demo

Above image demonstrates the working of @ParameterizedTest . As we have


provided 3 different csv source values which are comma-separated, so the
first argument to test method is a String and the second argument is an
integer type, therefore the test case ran 3 times. Also, all string and integer
values provided by csv source are not null and integer value is not 0,
therefore assertNotNull and assertNotEquals passes for all values passed.
In the next lesson, we will be studying parameterized tests with
@CsvFileSource .
Parameterized Test with @CsvFileSource

This lesson demonstrates the use of @CsvFileSource to pass different arguments to @ParameterizedTest.

WE'LL COVER THE FOLLOWING

• @CsvFileSource

@CsvFileSource #
@CsvFileSource allows you to use CSV files from the classpath. This csv file
gets picked up from the classpath at the time of running test case and each
line from a CSV file results in one invocation of the parameterized test. We
can also provide a number of lines to skip from top to take comma-separated
values.

Let’s look at a demo.

Step 1 - Let’s assume that we have to write a parameterized test that takes
values from @CsvFileSource .

Step 2 - We create a csv file by name, capitals.csv . It has comma-separated


values of countries and their capitals.

Step 3 - We will keep this csv file on the classpath.

capitals.csv

Country, Capital
India, New Delhi
France, Paris
United States, Washington D.C.
United Kingdom, London

Step 4 - We create a test class by name, CsvFileSourceTest.java .

Step 5 - It contains a test method by name, testWithCsvFileSource method. In


order to provide different parameters/values to the same test method, this
method is marked as @ParameterizedTest instead of @Test .
Step 6 - In order to provide different and multiple values through csv file
source we mark this test method with @CsvFileSource annotation. This
annotation takes resources which is the path to the csv file and
numLinesToSkip which an integer value, to let test method skip those many
lines while providing arguments to @ParameterizedTest .

Let’s see the test class below.

CsvFileSourceTest.java

package com.hubberspot.junit5.parameterized;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;

class CsvFileSourceTest {

@ParameterizedTest
@CsvFileSource(resources = "/capitals.csv", numLinesToSkip = 1)
void testWithCsvFileSource(String country, String capital) {
assertNotNull(country);
assertNotNull(capital);
}

Output of @ParameterizedTest demo

Above image demonstrates the working of @ParameterizedTest . As we have


provided 4 different csv file source values which are comma separated, so the
first argument to test method is a String which is country and second

argument is a String which is capital, therefore the test case ran 4 times. Also,
all string values provided by csv file source are not null, therefore
assertNotNull passes for all values passed.

In the next lesson we will be studying Assumptions in Junit 5.


@RepeatedTest example

This lesson demonstrates how to use @RepeatedTest annotation to run tests multiple times.

WE'LL COVER THE FOLLOWING

• @Repeated Tests
• Explanation

@Repeated Tests #
JUnit 5 Jupiter provides the ability to repeat a test a specified number of times.
It is done by simply annotating a method with @RepeatedTest . To this
annotation, we specify a number which is the total number of repetitions
desired. For each and every invocation of a repeated test, it behaves like the
execution of a regular @Test method. Also, each test is executed with support
for the same lifecycle callbacks and extensions. Instead of using @Test
annotation, we use @RepeatedTest annotation.

Let’s take a look at a demo.

package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.RepeatedTest;

public class RepeatedTestDemo {

@RepeatedTest(5)
public void simpleRepeatedTest() {
assertTrue(0 < 5);
}

}
Explanation #
On running RepeatedTestDemo.java as JUnit Test case, the output generated is
demonstrated in the above image.

@RepeatedTest annotation takes in a value of type integer. This integer value is


the count of the number of times the test case will be executed. The output
image above tells us the format in which it is run -

"repetition " + {currentRepetition} + " of " + {totalRepetitions} ;

where currentRepetition is the current repetition count and


totalRepetitions is the total number of times the test case will repeat its
execution.

In the next lesson, we will discuss about @RepeatedTest with DisplayName .


@RepeatedTest with Display Name

This lesson demonstrates how to use @RepeatedTest annotation with a custom display name.

WE'LL COVER THE FOLLOWING

• @Repeated Tests with @DisplayName


• Explanation

@Repeated Tests with @DisplayName #


In our previous lesson, we saw how to use @RepeatedTest annotation to run
tests multiple times. @RepeatedTest takes in a value of type integer. This
integer value is the count of the number of times the test case will be
executed. The output of Junit Test case in the previous lesson had the default
display name for the test case. In this lesson, we can also provide custom
display name using @DisplayName annotation over @RepeatedTest . The name
attribute of @RepeatedTest can be used to provide a custom display name.

Let’s look into a demo.

RepeatedTestWithDisplayNameDemo.java

package com.hubberspot.junit5.repeated;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.RepeatedTest;

public class RepeatedTestWithDisplayNameDemo {

@RepeatedTest(name="{displayName} - {currentRepetition}/{totalRepetitions}",
value = 5)
@DisplayName("Repeated test")
public void repeatedTestWithDisplayName() {
assertTrue(0 < 5);
}

}
package io.educative.junit5;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.RepeatedTest;

public class RepeatedTestWithDisplayNameDemo {

@RepeatedTest(name="{displayName} - {currentRepetition}/{totalRepetitions}",
value = 5)
@DisplayName("Repeated test")
public void repeatedTestWithDisplayName() {
assertTrue(0 < 5);
}

Explanation #
On running RepeatedTestWithDisplayNameDemo.java as JUnit Test case, the
output generated is demonstrated in the above image.

@RepeatedTest annotation takes in a name attribute of type String. This name


value overrides default name of @RepeatedTest . Using below static
placeholders in name attribute will override existing default names -

{displayName} : display name of the @RepeatedTest method

{currentRepetition} : the current repetition count


{totalRepetitions} : the total number of repetitions

The above demo shows that the Junit test case ran with below format -

{displayName} - {currentRepetition} / {totalRepetitions}

This marks the end of the course, hope you enjoyed learning.
Conclusion

WE'LL COVER THE FOLLOWING

• Thank you !!!


• Next Steps
• Video Tutorials
• Feedback

Thank you !!! #


I hope that this course was a good learning experience for you. Thank you for
following through with it to the end.

Next Steps #
This course touched usage of JUnit 5 features. For further reading follow:-

https://junit.org/junit5/docs/current/user-guide/

For complete JUnit 5 video course, please visit -

https://www.udemy.com/course/java-unit-testing-with-junit-5/?
referralCode=14BA45216871EF2F4095

Video Tutorials #
For more on such technologies visit our Youtube channel at -

https://www.youtube.com/user/hubberspot?sub_confirmation=1

Feedback #
For feedback, comments, and suggestions, please contact us at
java.hubberspot@gmail.com

You might also like