JUnit 5: How to assert an exception is thrown?
To read a text file in Java, you can use the BufferedReader class from the java.io package.
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:
Import required JUnit classes
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;First, define the class and method that will throw the exception:
class MyClass {
public int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
}
}Example: Asserting an exception is thrown
@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. Note that the second argument must implement the Executable functional interface (typically provided as a lambda). 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.
You can also capture the thrown exception to perform additional assertions. Note that assertThrows returns the thrown exception instance, allowing you to inspect it further:
@Test
public void testDivideByZeroWithCapture() {
MyClass myClass = new MyClass();
ArithmeticException ex = assertThrows(ArithmeticException.class, () -> myClass.divide(10, 0));
assertEquals("Division by zero", ex.getMessage());
}