@Test public void testOverwithdraw() { // Create a checking account. Checking acc = new Checking(...); try { // Withdraw an amount that should cause an exception of type InsufficientFundsException... acc.withdraw( new Money(200, 0) ); // If we reach this point in the code, that means the exception was not thrown as expected, so this test case fails. fail(); } catch (InsufficientFundsException ife) { System.out.println("InsufficientFunds Exception on testOverwithdraw"); ife.printStackTrace(); } }
An alternative way to test that an InsufficientFundsException was thrown appropriately:
@Test public void whenExceptionThrown_thenAssertionSucceeds() { Exception exception = assertThrows(InsufficientFundsException.class, () -> { // Create a checking account. Checking acc = new Checking(...); // Withdraw an amount that should cause an exception of type InsufficientFundsException... acc.withdraw( new Money(200, 0) ); }); String expectedMessage = "Trying to withdraw too much"; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); }