When writing unit tests for methods that throw exceptions, it's important to verify both expected and unexpected behaviours. Java provides mechanisms like try-catch blocks to test exception handling effectively.
In cases where a method should execute without throwing an exception, wrap the call in a try-catch block. If an exception is caught, the test should fail, indicating unexpected behavior. Additionally, assert that the method has performed the intended effect.
@Test
void testDepositSuccess() {
try {
double bal = myAccount.deposit(120.0);
assertEquals(expectedBalance, bal, 0.01);
} catch (NegativeAmountException e) {
fail("Caught NegativeAmountException");
}
}
Here, if the method works as expected, it updates the balance without throwing an exception. If an exception is caught, the test fails.
When a method is expected to throw an exception for invalid input, the test should verify that the exception occurs. If no exception is thrown, the test should fail, indicating incorrect behavior.
@Test
void testDepositExceptionExpected() {
try {
myAccount.deposit(-5.0);
fail("Exception not thrown!");
} catch (NegativeAmountException e) { }
// Ensure the balance remains unchanged
assertEquals(previousBalance, myAccount.getBalance(), 0.01);
}