JUnit 5 Assertions with Examples

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

September 21, 2022

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.

A 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
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 SuppliermessageSupplier = () -> "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 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 SuppliermessageSupplier = () -> "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 messageSupplier)
void testCase() < //Test will pass Assertions.assertArrayEquals(new int[], new int[], "Array Equal Test"); //Test will fail because element order is different Assertions.assertArrayEquals(new int[], new int[], "Array Equal Test"); //Test will fail because number of elements are different Assertions.assertArrayEquals(new int[], new int[], "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 messageSupplier)
@Test void testCase() < IterablelistOne = new ArrayList<>(Arrays.asList(1,2,3,4)); Iterable listTwo = new ArrayList<>(Arrays.asList(1,2,3,4)); Iterable listThree = new ArrayList<>(Arrays.asList(1,2,3)); Iterable 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 messageSupplier) public static void assertEquals(Object actual) public static void assertEquals(Object actual, String message) public static void assertEquals(Object actual, Supplier 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 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 messageSupplier) public static void assertTimeout(Duration timeout, ThrowingSupplier supplier, String message) public static void assertTimeout(Duration timeout, ThrowingSupplier supplier, Supplier 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()

T he 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 messageSupplier) public static void assertTrue(BooleanSupplier booleanSupplier) public static void assertTrue(BooleanSupplier booleanSupplier, String message) public static void assertTrue(BooleanSupplier booleanSupplier, Supplier messageSupplier) public static void assertFalse(boolean condition) public static void assertFalse(boolean condition, String message) public static void assertFalse(boolean condition, Supplier messageSupplier) public static void assertFalse(BooleanSupplier booleanSupplier) public static void assertFalse(BooleanSupplier booleanSupplier, String message) public static void assertFalse(BooleanSupplier booleanSupplier, Supplier 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 ()

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 assertThrows(Class 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 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"; >>