JUnit 5 Assertions
Assertion
JUnit 5 provides an assertion class named Assertions. Assertions verify values or behavior that a test wants to check.
Value Assertions
JUnit provides basic assertion methods.
assertEquals
assertEquals(expected, actual, {message}) checks whether the actual value equals the expected value.
assertNull(actual)
assertNull(actual, {message}) checks whether a value is null.
assertNotNull(actual)
assertNotNull(actual, {message}) checks whether a value is not null.
assertTrue(boolean)
assertTrue(actual, {message}) checks whether the condition is true.
assertFalse(boolean)
assertFalse(actual, {message}) checks whether the condition is false.
Convenient Assertions
Besides value assertions, JUnit provides useful assertion helpers.
assertAll(executable...)
assertAll runs multiple assertions together. If ordinary assertions are written one after another, execution stops when an earlier assertion fails, so later failures are not visible. With assertAll, the results of all assertions can be checked.
assertThrows(expectedType, executable)
assertThrows checks whether an exception is thrown. The returned exception can also be used to check the exception message.
assertTimeout(duration, executable)
assertTimeout checks whether execution completes within a specified time. The test completes after the lambda expression passed as the second argument ends.
assertTimeoutPreemptively(duration, executable)
assertTimeoutPreemptively also checks whether execution completes within a specified time. The difference from assertTimeout is that assertTimeout waits until execution finishes, whereas assertTimeoutPreemptively aborts the test as soon as the specified time passes.
Other Assertion Libraries
JUnit 5 can use other assertion libraries. By adding dependencies such as AssertJ or Hamcrest, they can be used much like in JUnit 4.
AssertJ
AssertJ supports method chaining, so it helps write cleaner and more readable test code. Add org.assertj:assertj-core as a test dependency before using it.