The JUnit unit testing framework provides three methods for testing exceptions: 1. Expected exception assertion, which allows you to specify the type of exception expected to be thrown; 2. Exception message assertion, which can verify whether the exception has the expected message; 3. Exception cause assertion, Used to verify the root cause of an exception.
JUnit Unit Testing Framework: The Best Way to Test Exceptions
JUnit is a unit testing framework widely used by Java developers. It provides various assertion methods to verify the expected results of the test. For testing exceptions, JUnit provides a set of specialized methods.
1. Expected exception assertion
@Test(expected = ExceptionClass.class)
Annotations allow us to specify specific exceptions that should be thrown in the test method type. If the expected exception is not thrown, the test will fail.
@Test(expected = NullPointerException.class) public void testNullPointerException() { String str = null; str.toUpperCase(); }
2. Exception message assertion
Using the assertThrowWithMessage
method, we can not only verify whether an exception is raised, but also verify whether its message As expected.
@Test public void testExceptionMessage() { Exception exception = assertThrows(Exception.class, () -> { throw new Exception("Custom Exception"); }); assertEquals("Custom Exception", exception.getMessage()); }
3. Exception cause assertion
Using the assertCause
method, we can verify the root cause of the exception (if any).
@Test public void testExceptionCause() { Exception cause = new Exception("Cause Exception"); Exception exception = new Exception("Actual Exception", cause); Exception actualCause = assertThrows(Exception.class, () -> { throw exception; }).getCause(); assertEquals(cause, actualCause); }
Practical case
In the following example, we use JUnit to test a method that may throw an ArithmeticException
exception:
public class Calculator { public int divide(int numerator, int denominator) { if (denominator == 0) { throw new ArithmeticException("Cannot divide by zero"); } return numerator / denominator; } } @ExtendWith(SpringExtension.class) public class CalculatorTest { @Test(expected = ArithmeticException.class) public void testDivideByZero() { Calculator calculator = new Calculator(); calculator.divide(10, 0); } }
Tip
The above is the detailed content of JUnit unit testing framework: The best way to test exceptions. For more information, please follow other related articles on the PHP Chinese website!