Test using JUnit (e.g. using ExplorerTest.java):
// Test that GameOverException is thrown appropriately
@Test
public void testGameOverByFallingInWater() {
try {
Island isle = new Island();
Location dest = new Location(0, -1); // a location that is not on the island
_explorer.checkWater(isle, dest);
// If we reach this point in the code, that means the exception was not thrown as expected, so this test case fails.
fail();
}
catch (GameOverException e) {
System.out.println("GameOverException on testGameOverByFallingInWater");;
e.printStackTrace();
}
}
- An alternative way to test that a GameOverException was thrown appropriately:
@Test
public void whenExceptionThrown_thenAssertionSucceeds() {
Exception exception = assertThrows(GameOverException.class, () -> {
Island isle = new Island();
Location dest = new Location(0, -1); // a location that is not on the island
_explorer.checkWater(isle, dest);
});
String expectedMessage = "You fell in the water.";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}