JUnit is a robust and widely used testing framework for Java. This plays an important role in making sure the software is reliable. It provides developers with a great structure for creating and executing test cases. Junit features help to embrace a test-driven development approach, that ensures confidence in the application. One of the main things in Junit is assertions that help developers validate the output with the desired result. In this article, we will go through JUnit 5 Assertions in detail and explore their work.
Prerequisites
To work with JUnit 5 assertions, make sure you have the following:
A basic understanding of JUnit 5.
A Java development environment (e.g., Eclipse, IntelliJ, or any other IDE of your choice)
A project configured with JUnit 5 dependencies.
JUnit 5 Assertions
The Assertions class in JUnit 5 has a set of methods that helps in making assertions in your tests. These help in comparing the code output with your desired result. These methods cover a wide range of conditions. These include equality, nullity, truthiness, and many more.
Common Assertions in JUnit 5
Below are common assertions in Junit.
assertEquals (expected, actual): Asserts that the expected and actual values are equal.
assertNotEquals(expected, actual): Asserts that the expected values and the actual values are not equal.
assertTrue(condition): This asserts whether the given condition is true. Test case passes if it's true and fails if not.
assertFalse(condition): This asserts whether the given condition is false. Test case passes if it's false and fails if not.
assertNull(value): This asserts whether the given value is null. Test case passes if it's null and fails if not.
assertNotNull(value): This asserts whether the given value is not null. Test case passes if it's not null and fails if not.
assertArrayEquals(expectedArray, actualArray): This asserts whether the expected and actual arrays are equal. Test case passes if they're equal and fails if not.
assertSame(expected, actual): This asserts whether the expected and actual references point to the same object. Test case passes if it's true and fails if not.
assertNotSame(expected, actual): This asserts whether the expected and actual references do not point to the same object. Test case passes if it's true and fails if not.
assertThrows(exceptionType, executable): This asserts whether the executable throws an exception of the specified type. Test case passes if it throws an exception and fails if not.
Example of JUnit 5 Assertions
Below is the Junit code along with its respective Java code which demonstrates the working of all assertions stated above.