JUnit 5 Assertions
Different assertion methods that are available in JUnit 5
Assertion methods in JUnit 5:
- assertTrue
- assertFalse
- assertNull
- assertNotNull
- assertEquals
- assertNotEquals
- assertArrayEquals
- assertIterableEquals
- assertThrows
- assertDoesNotThrow
assertTrue and assertFalse
assertTrue validates that the argument is true and assertFalse validates that the argument is false. They throw AssertionFailedError otherwise.
assertNull and assertNotNull
assertNull validates that the argument is null and assertNotNull validates that the argument is not null. They throw AssertionFailedError otherwise.
assertEquals and assertNotEquals
assertEquals validates that the arguments are equal and assertNotEquals validates that the arguments are not equal. They throw AssertionFailedError otherwise.
assertSame
Validates that the arguments point to the same object (same reference). Check out this article for the difference between assertEquals and assertSame.
assertArrayEquals
Validates that the arrays are deeply equal.
It basically loops over the elements and calls the equals() method for the elements at every index. If the array is of primitive types, then it directly uses the equality operator (==).
If the element is an array (in case of 2D array), then it loops over those elements as well and repeats the process.
assertIterableEquals
Validates that two iterable collections are equal. Throws AssertionFailedError if the contents differ.
assertThrows
assertThrows can be used to assert exceptions thrown by the method under test.
Main parameters:
- The exception type that is expected to be thrown.
- An executable object that invokes the method/functionality under test.
The below example is to test that the code throws IndexOutOfBoundsException.
We can also validate the state that is exposed by the exception object. The assertThrows method returns the exception that is thrown and we can add validations on the exception object as well.
The below example extends the above example, but also verifies the error message from the exception.
assertDoesNotThrow
This can be used to validate that no exception is thrown by the functionality under test.
You can also verify the output/return value of the code if no exception is thrown.
assertAll
The assertAll method can be used to group multiple assertions.
Check out this article for more details on assertAll
Here’s the code for the above examples
I hope you have learned something from the article. Feel free to ask any questions or share any comments you have about the article.
Happy Coding!