Eroxl's Notes
Testing Exceptions

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.

1. Testing Successful Execution (No Exception Expected)

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.

Example

@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.

2. Testing Expected Exceptions

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.

Example

@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);
}