Marshall Tigerus Marshall Tigerus - 11 months ago 80
Java Question

JUnit 4 Expected Exception type

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"); = name;
this.numGold = initialGold; = Pirate.DEFAULT_HEALTH;
this.isCursed = false;

My JUnit Code snippet:

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());

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.

Answer Source

There's actually an alternative to the @Test(expected=Xyz.class) in JUnit 4.7 using Rule and ExpectedException

In your test case you declare an ExpectedException annotated with @Rule, and assign it a default value of ExpectedException.none(). Then in your test that expects an exception you replace the value with the actual expected value. The advantage of this is that without using the ugly try/catch method, you can further specify what the message within the exception was

@Rule public ExpectedException thrown= ExpectedException.none();

public void myTest() {
    thrown.expect( Exception.class );
    thrown.expectMessage("Init Gold must be >= 0");

    rodgers = new Pirate("Dread Pirate Rodgers" , -100);

Using this method, you might be able to test for the message in the generic exception to be something specific.

ADDITION Another advantage of using ExpectedException is that you can more precisely scope the exception within the context of the test case. If you are only using @Test(expected=Xyz.class) annotation on the test, then the Xyz exception can be thrown anywhere in the test code -- including any test setup or pre-asserts within the test method. This leads to a false positive.

Using ExpectedException, you can defer specifying the thrown.expect(Xyz.class) until after any setup and pre-asserts, just prior to actually invoking the method under test. Thus, you more accurately scope the exception to be thrown by the actual method invocation rather than any of the test fixture itself.

JUnit 5 NOTE:

JUnit 5 will be removing @Test(expected=...), @Rule and ExpectedException altogether. They will be replaced with the new assertThrows() and expectThrows(), but will require the use of Java 8 and lambda syntax.