JUnit 5 Assertions with Examples

JUnit 5 assertions help in validating the expected output with the actual output of a test. To keep things simple, all JUnit Jupiter assertions are static methods in the org.junit.jupiter.Assertions class.

failed assertion will throw an AssertionFailedError or a subclass of it.

1. Assert Object Equality – assertEquals() and assertNotEquals()

Use Assertions.assertEquals() to assert that expected value and actual value are equal. assertEquals() has many overloaded methods for different data types e.g., int, short, float, char etc. It also supports passing error messages to be printed in case the test fails. e.g.

public static void assertEquals(int expected, int actual)
public static void assertEquals(int expected, int actual, String message)
public static void assertEquals(int expected, int actual, Supplier<String< messageSupplier)
void test() 
{
    //Test will pass
    Assertions.assertEquals(4, Calculator.add(2, 2));
     
    //Test will fail 
    Assertions.assertEquals(3, Calculator.add(2, 2), "Calculator.add(2, 2) test failed");
     
    //Test will fail 
    Supplier<String> messageSupplier  = () -> "Calculator.add(2, 2) test failed";
    Assertions.assertEquals(3, Calculator.add(2, 2), messageSupplier);
}

Similarly, Assertions.assertNotEquals() method is used to assert that expected value and actual value are NOT equal. In contrast to assertEquals(), assertNotEquals() does not contain overloaded methods for different data types but only Object is accepted.

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> messageSupplier)
void test()
{
	//Test will pass
	Assertions.assertNotEquals(3, Calculator.add(2, 2));

	//Test will fail
	Assertions.assertNotEquals(4, Calculator.add(2, 2), "Calculator.add(2, 2) test failed");

	//Test will fail
	Supplier<String> messageSupplier  = () -> "Calculator.add(2, 2) test failed";
	Assertions.assertNotEquals(4, Calculator.add(2, 2), messageSupplier);
}

2. Assert Array Equality – assertArrayEquals()

The assertArrayEquals() method asserts that expected and actual arrays are equal.

It also has overloaded methods for different data types e.g. boolean[], char[], int[] etc. It also supports passing error messages to be printed in case the test fails. e.g.

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> messageSupplier)
void testCase()
{
	//Test will pass
	Assertions.assertArrayEquals(new int[]{1,2,3}, new int[]{1,2,3}, "Array Equal Test");

	//Test will fail because element order is different
	Assertions.assertArrayEquals(new int[]{1,2,3}, new int[]{1,3,2}, "Array Equal Test");

	//Test will fail because number of elements are different
	Assertions.assertArrayEquals(new int[]{1,2,3}, new int[]{1,2,3,4}, "Array Equal Test");
}

3. Assert Iterable Equality – assertIterableEquals()

It asserts that expected and actual iterables are deeply equal. Deeply equal means that the number and order of elements in the collection must be the same, and iterated elements must be equal.

It also has three overloaded methods.

public static void assertIterableEquals(Iterable<?> expected, Iterable> actual)
public static void assertIterableEquals(Iterable<?> expected, Iterable> actual, String message)
public static void assertIterableEquals(Iterable<?> expected, Iterable> actual, Supplier<String> messageSupplier)
@Test
void testCase()
{
     Iterable<Integer> listOne = new ArrayList<>(Arrays.asList(1,2,3,4));
     Iterable<Integer> listTwo = new ArrayList<>(Arrays.asList(1,2,3,4));
     Iterable<Integer> listThree = new ArrayList<>(Arrays.asList(1,2,3));
     Iterable<Integer> listFour = new ArrayList<>(Arrays.asList(1,2,4,3));

    //Test will pass
    Assertions.assertIterableEquals(listOne, listTwo);

    //Test will fail
    Assertions.assertIterableEquals(listOne, listThree);

    //Test will fail
    Assertions.assertIterableEquals(listOne, listFour);
}

4. Assert String Lines – assertLinesMatch()

It asserts that the expected list of Strings matches the actual list. The logic to match a string with another string is :

  1. check if expected.equals(actual) – if yes, continue with next pair
  2. otherwise, treat expected as a regular expression and check via
    String.matches(String) – if yes, continue with next pair
  3. otherwise, check if expected line is a fast-forward marker, if yes apply
    fast-forward actual lines accordingly and goto 1.

A valid fast-forward marker is a string that starts and ends with >> and contains at least four characters. Any character between the fast-forward literals is discarded.

>>>>
>> stacktrace >>
>> single line, non Integer.parse()-able comment >>

5. Assert Nulls – assertNotNull() and assertNull()

The assertNotNull() asserts that actual is NOT null. Similarly, assertNull() method asserts that actual is null. Both have three overloaded methods.

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

public static void assertEquals(Object actual)
public static void assertEquals(Object actual, String message)
public static void assertEquals(Object actual, Supplier<String> messageSupplier)
@Test
void testCase()
{
	String nullString = null;
	String notNullString = "howtodoinjava.com";

	//Test will pass
	Assertions.assertNotNull(notNullString);

	//Test will fail
	Assertions.assertNotNull(nullString);

	//Test will pass
	Assertions.assertNull(nullString);

	// Test will fail
	Assertions.assertNull(notNullString);
}

6. Assert Object References – assertNotSame() and assertSame()

The assertNotSame() asserts that expected and actual DO NOT refer to the same object. Similarly, assertSame() method asserts that expected and actual refer to the exact same object.

Both have three overloaded methods.

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

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> messageSupplier)
@Test
void testCase()
{
	String originalObject = "howtodoinjava.com";
	String cloneObject = originalObject;
	String otherObject = "example.com";

	//Test will pass
	Assertions.assertNotSame(originalObject, otherObject);

	//Test will fail
	Assertions.assertNotSame(originalObject, cloneObject);

	//Test will pass
	Assertions.assertSame(originalObject, cloneObject);

	// Test will fail
	Assertions.assertSame(originalObject, otherObject);
}

7. Assert Timeouts – assertTimeout() and assertTimeoutPreemptively()

The assertTimeout() and assertTimeoutPreemptively() methods are used to test long-running tasks. If a given task inside the test takes more than the specified duration, then the test will fail.

The only difference between both methods is that in assertTimeoutPreemptively(), execution of the Executable or ThrowingSupplier will be preemptively aborted if the timeout is exceeded. In case of assertTimeout(), Executable or ThrowingSupplier will NOT be aborted.

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> messageSupplier)
public static void assertTimeout(Duration timeout, ThrowingSupplier<T> supplier, String message)
public static void assertTimeout(Duration timeout, ThrowingSupplier<T> supplier, Supplier<String> messageSupplier)
@Test
void testCase() {

	//This will pass
	Assertions.assertTimeout(Duration.ofMinutes(1), () -> {
		return "result";
	});

	//This will fail
	Assertions.assertTimeout(Duration.ofMillis(100), () -> {
		Thread.sleep(200);
		return "result";
	});

	//This will fail
	Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> {
		Thread.sleep(200);
		return "result";
	});
}

8. Assert Booleans – assertTrue() and assertFalse()

The assertTrue() asserts that the supplied condition is true or boolean condition supplied by BooleanSupplier is true.

Similarly, assertFalse() asserts that supplied condition is false.

Both have the following overloaded methods:

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> messageSupplier)

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> messageSupplier)
@Test
void testCase() {

	boolean trueBool = true;
	boolean falseBool = false;

	Assertions.assertTrue(trueBool);
	Assertions.assertTrue(falseBool, "test execution message");
	Assertions.assertTrue(falseBool, AppTest::message);
	Assertions.assertTrue(AppTest::getResult, AppTest::message);

	Assertions.assertFalse(falseBool);
	Assertions.assertFalse(trueBool, "test execution message");
	Assertions.assertFalse(trueBool, AppTest::message);
	Assertions.assertFalse(AppTest::getResult, AppTest::message);
}

private static String message () {
	return "Test execution result";
}

private static boolean getResult () {
	return true;
}

9. Assert Errors – assertThrows()

The assetThrows() asserts that execution of the supplied Executable throws an exception of the expectedType and returns the exception.

public static <T extends Throwable> T assertThrows(Class<T> expectedType, 
	Executable executable)
@Test
void testCase() {

	Throwable exception = Assertions.assertThrows(IllegalArgumentException.class, () -> {
        throw new IllegalArgumentException("error message");
    });
}

10. Assert Test Failures – fail()

The fail() method fails the test. It has the following overloaded methods:

public static void fail(String message)
public static void fail(Throwable cause)
public static void fail(String message, Throwable cause)
public static void fail(Supplier<String> messageSupplier)
public class AppTest {
	@Test
	void testCase() {

		Assertions.fail("not found good reason to pass");
		Assertions.fail(AppTest::message);
	}

	private static String message () {
		return "not found good reason to pass";
	}
}

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.