Search⌘ K

Assert Methods

Explore various assert methods in this lesson to write effective unit tests using JUnit in Spring. Understand how to verify conditions with assertEquals, assertTrue, assertNull, and handle exceptions with assertThrows. Learn to combine multiple assertions with assertAll for comprehensive test coverage.

There are a number of assert methods that are available with the import of the Assertions.* package.

assertEquals()

The assertEquals() method compares two values — the expected value and the actual value — to determine whether or not both are the same. A test method from the last lesson using assertEquals() is reproduced here:

Java
@Test
public void testfindIndex_numberNotInArray() {
ArrayMethods arrayMethods = new ArrayMethods();
assertEquals(-1, arrayMethods.findIndex(new int[]{8,4,5}, 1));
}

There are many variations of assertEquals() with different data types. An optional third String argument can be added that contains a message about what the test is for. This feature is handy for a code base spanning thousands of lines, where the developer might not know what a failing test intended to do. We will change the testfindIndex_numberNotInArray ...