Java
Assertions
Learn assertions with assertEquals and assertTrue.
Assertions
The Assertions class provides static methods that verify test results. The most common are assertEquals, assertTrue, assertFalse and assertNull.
import static org.junit.jupiter.api.Assertions.*;
assertEquals(5, result);
assertTrue(result > 0);
assertNull(object);
The first argument is the expected value, the second is the actual. If they do not match, the test fails and the framework reports the error. assertThrows expects an exception to be thrown; this is used to test error paths.
assertThrows
For tests that expect a method to throw an exception, use assertThrows. The first argument is the expected exception class, the second is a lambda that runs the code.
assertThrows(ArithmeticException.class, () -> {
int quotient = 10 / 0;
});
If the exception is thrown, the test passes; if not, it fails. This is a safe way to verify negative scenarios and is shorter than writing try/catch. The returned exception object can also be checked further.
Exercise Write assertions for a Divider
Define a Divider class with a divide(int a, int b) method that returns a / b. In a DividerTest class, write a @Test method testDivide that verifies with assertEquals(5, d.divide(10, 2)). Also call assertThrows(ArithmeticException.class, () -> d.divide(10, 0)). Add a main method that prints divide(10, 2).
Show example solution
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class Divider {
int divide(int a, int b) {
return a / b;
}
}
class DividerTest {
@Test
void testDivide() {
Divider d = new Divider();
assertEquals(5, d.divide(10, 2));
assertThrows(ArithmeticException.class, () -> d.divide(10, 0));
}
public static void main(String[] args) {
Divider d = new Divider();
System.out.println(d.divide(10, 2));
}
}
Test yourself
-
Complete the assertTrue call
int result = 7;
____(result > 0);
Show answer
int result = 7;
assertTrue(result > 0);
-
What should be the first argument of assertThrows?
- An error message string
- A lambda expression
- The value to verify
- The expected exception class
Show answer
The expected exception class — The first argument is the expected exception class (e.g. ArithmeticException.class).
-
Match assertions to their purpose
- assertEquals
- Value equality
- assertTrue
- Condition is true
- assertNull
- Value is null
- assertThrows
- Expects an exception
Next lesson: @BeforeEach and @AfterEach