What is Exception Test in JUnit?
In JUnit, an exception test is used to verify that a method throws a specific exception under certain conditions. It's a type of negative test to ensure your code fails gracefully when given invalid inputs or when something unexpected occurs.
Why Use Exception Tests?
Exception tests are useful to:
Validate input checks.
Ensure robust error handling.
Test edge cases and defensive programming logic.
How to Write Exception Tests in JUnit
JUnit 4: Using
@Test(expected = Exception.class)
import org.junit.Test; public class ExceptionTestExample { @Test(expected = ArithmeticException.class) public void testDivideByZero() { int result = 10 / 0; // This will throw ArithmeticException } }
Explanation:
If
ArithmeticExceptionis thrown, the test passes.If no exception or a different one is thrown, the test fails.
JUnit 5: Using
Assertions.assertThrows()
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertThrows; public class ExceptionTestExample { @Test void testDivideByZero() { assertThrows(ArithmeticException.class, () -> { int result = 10 / 0; }); } }
Explanation:
assertThrows()checks whether the given lambda throws the specified exception.It gives more flexibility (example: checking exception message or stack trace).
Example: Custom Exception Test (JUnit 5)
class InvalidAgeException extends RuntimeException { public InvalidAgeException(String message) { super(message); } } class Person { public void setAge(int age) { if (age < 0) { throw new InvalidAgeException("Age cannot be negative"); } } } import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class PersonTest { @Test void testInvalidAgeException() { Person person = new Person(); Exception exception = assertThrows(InvalidAgeException.class, () -> { person.setAge(-5); }); assertEquals("Age cannot be negative", exception.getMessage()); } }
At a glance:
| Feature | JUnit 4 | JUnit 5 |
|---|---|---|
| Exception Test Syntax | @Test(expected = Exception.class) | assertThrows(Exception.class, () -> {...}) |
| Can check message | No | Yes |
| Recommended for new code | No, because syntax is old | Yes, because of flexibility |
No comments:
Post a Comment