Assertions

JUnit provides a variety of assertion methods in the org.junit.Assert class (or in later versions, you can use org.junit.jupiter.api.Assertions in JUnit 5). These assertions help you check whether the expected result of a test matches the actual result. Here are some common and useful JUnit assertions:

assertEquals:

  • Compares two values for equality
assertEquals(expected, actual);

assertNotEquals:

  • Asserts that two values are not equal.
assertNotEquals(notExpected, actual);

assertTrue / assertFalse:

  • Asserts that a condition is true or false.
assertTrue(condition);
assertFalse(condition);

assertThrows (JUnit 5):

  • Asserts that the execution of a given executable (e.g., a lambda or method reference) throws an exception of a specific type.
assertThrows(Exception.class, () -> {
    // Code that should throw an exception
});