I am trying to do a JUnit test on code that someone else has written, but I cannot figure out how to test for the exception, because the exception seems to lack a type.
public Pirate(String name, int initialGold) throws Exception {
if(initialGold < 0)
throw new Exception("Init Gold must be >= 0");
this.name = name;
this.numGold = initialGold;
this.health = Pirate.DEFAULT_HEALTH;
this.isCursed = false;
}
My JUnit Code snippet:
@Test
public static void constructorTest() throws Exception{
rodgers = new Pirate("Dread Pirate Rodgers", 10000);
assertEquals("Dread Pirate Rodgers" , rodgers.getName());
assertEquals(10000, rodgers.getNumGold());
assertEquals(100, rodgers.getHealth());
assertEquals(false, rodgers.getIsCursed());
}
@Test()
public static void exceptionTest() throws Exception{
rodgers = new Pirate("Dread Pirate Rodgers" , -100);
}
I know I need to put expected = (some type of exception) in the parenthesis of test, but I am clueless as to the exception type.
Exception
, but that's a bad choice - it should probably beIllegalArgumentException
. Either way, your test basically needs to check that the right exception is thrown - but it's up to you to decide what that type is.