37

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.

7
  • 1
    Run the test and see what happens.
    – Mateusz
    May 23, 2013 at 20:56
  • 3
    You're writing a test: you want to verify that a particular type of exception is thrown. Currently you're actually throwing Exception, but that's a bad choice - it should probably be IllegalArgumentException. 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.
    – Jon Skeet
    May 23, 2013 at 20:57
  • Why is rodgers a class field? May 23, 2013 at 20:57
  • The code under test is throwing Exception - that's the type that you should put in your expected = ..... clause. ( Exception is actually java.lang.Exception )
    – DaveH
    May 23, 2013 at 21:00
  • 5
    I'm sure I'm going to regret this, but the Pirate class should raise an "wannabe" exception for any "Dread" pirates not named "ROBERTS" Yeah, yeah - go ahead and down-mod me :-) en.wikipedia.org/wiki/Dread_Pirate_Roberts
    – Bukes
    Oct 12, 2013 at 2:25

4 Answers 4

110

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

@Test
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 can lead 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 JUnit Jupiter has removed @Test(expected=...), @Rule and ExpectedException altogether. They are replaced with the new assertThrows(), which requires the use of Java 8 and lambda syntax. ExpectedException is still available for use in JUnit 5 through JUnit Vintage. Also JUnit Jupiter will also continue to support JUnit 4 ExpectedException through use of the junit-jupiter-migrationsupport module, but only if you add an additional class-level annotation of @EnableRuleMigrationSupport.

2
  • 20
    +1, because you don't know exactly which line in the test throws the exception when you use @Test(expected=IllegalArgumentException.class). So if the wrong line throws the exception, the test will pass, but your code may have potential issue.
    – Kirin Yao
    Nov 12, 2013 at 16:09
  • 1
    Don't forget that the ExpectedException must be declared public.
    – Mats_SX
    Jan 20, 2014 at 11:46
20

You could either use expected in @Test annotation or provide an explicit catch block and issue a fail if the program flow is not as expected.

@Test(expected=Exception.class) // java.lang.Exception
public static void exceptionTest() throws Exception {
    rodgers = new Pirate("Dread Pirate Rodgers" , -100);
}

@Test
public static void exceptionTest() throws Exception {
    try {
        rodgers = new Pirate("Dread Pirate Rodgers" , -100);
        fail("should not reach this");
    } catch(Exception e) {
        // ok
    }
}

My personal preference is the first solution.

9

You can use JUnit 'expected' to test exceptions:

@Test(expected = ExceptionYouWishToTestFor.class)  
public void divisionWithException() {  
    // Test Code
}

After that it's up to you to throw that particular exception in your code.

7

I wouldn't throw an Exception if the gold isn't greater than or equal to zero. I would throw an IllegalArgumentException. It certainly sounds like it's illegal your Pirate to have a negative amount of gold.

public Pirate(String name, int initialGold) {
    if(initialGold < 0)
        throw new IllegalArgumentException("Init Gold must be >= 0");

Then in your JUnit test case, expect the IllegalArgumentException.

@Test(expected=IllegalArgumentException.class)
public static void exceptionTest() {
4
  • While I agree this is better implementation, I am not supposed to change the pirate class at all. May 23, 2013 at 21:08
  • 1
    If you cannot change the fact that the Pirate constructor throws Exception, then you'll just have to live with @Test(expected=Exception.class).
    – rgettman
    May 23, 2013 at 21:10
  • adding .class to it made it work properly and test properly, thanks May 23, 2013 at 21:11
  • 1
    Throws an Exception is not a good practice. You should make the exception more meaningful.
    – Kirin Yao
    Nov 12, 2013 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.