JUnit 5: How to assert an exception is thrown?
In JUnit 5, you can use the assertThrows method to assert that an exception is thrown when executing a certain piece of code. Here's an example of how to use it:
First, you need to import the required classes:
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;Now, let's say you have a method called divide that throws an ArithmeticException when dividing by zero:
@Test
public void testDivideByZero() {
// Arrange
MyClass myClass = new MyClass();
// Act & Assert
assertThrows(ArithmeticException.class, () -> myClass.divide(10, 0), "Division by zero should throw ArithmeticException");
}In this example, assertThrows checks if the lambda expression () -> myClass.divide(10, 0) throws an exception of type ArithmeticException. If the exception is thrown as expected, the test will pass; otherwise, it will fail. The optional third argument is a message that will be displayed if the test fails.