Asserting exceptions in Java, how?

<>

This question already has an answer here:

Answers


As other posters suggested, if you are using JUnit4, then you can use the annotation:

@Test(expected=NumberFormatException.class);

However, if you are using an older version of JUnit, or if you want to do multiple "Exception" assertions in the same test method, then the standard idiom is:

try {
   formatNumber("notAnumber");
   fail("Expected NumberFormatException");
catch(NumberFormatException e) {
  // no-op (pass)
}

Assuming you are using JUnit 4, call the method in your test in a way that causes it to throw the exception, and use the JUnit annotation

@Test(expected = NumberFormatException.class)

If the exception is thrown, the test will pass.


If you can use JUnit 4.7, you can use the ExpectedException Rule

@RunWith(JUnit4.class)
public class FooTest {
  @Rule
  public ExpectedException exception = ExpectedException.none();

  @Test
  public void doStuffThrowsIndexOutOfBoundsException() {
    Foo foo = new Foo();

    exception.expect(IndexOutOfBoundsException.class);
    exception.expectMessage("happened?");
    exception.expectMessage(startsWith("What"));
    foo.doStuff();
  }
}

This is much better than @Test(expected=IndexOutOfBoundsException.class) because the test will fail if IndexOutOfBoundsException is thrown before foo.doStuff()

See this article and the ExpectedException JavaDoc for details


You can do this:

 @Test(expected=IndexOutOfBoundsException.class)
    public void testIndexOutOfBoundsException() {
        ArrayList emptyList = new ArrayList();
        Object o = emptyList.get(0);
    }

Use @Test(expected=IOException.class)

http://junit.sourceforge.net/doc/faq/faq.htm#tests_7

This is fine if you have one expected exception. An alternative strategy is to add an Assert.fail() at the end of the test method. If an exception isn't thrown then the test will fail accordingly. e.g.

@Test
public void testIOExceptionThrown() {      
   ftp.write(); // will throw IOException      
   fail();
}

Add this annotation before your test method; it'll do the trick.

@Test(expected = java.lang.NumberFormatException.class)
public void testFooMethod() {
    // Add code that will throw a NumberFormatException
}

A solution that is not bound to a particular JUnit version is provided by catch-exception which has been made to overcome some disadvantages that are inherent in the JUnit mechanisms.


Need Your Help

Rails 3 SQLite3 Boolean false

ruby-on-rails ruby-on-rails-3 sqlite rails-activerecord

I'm trying to insert a false boolean value in a SQLite3 table but it always inserts a true value.

How to dismiss UIPopover from a button in the Popover

objective-c xcode ios ipad uipopovercontroller

I am trying to dismiss a UIPopoverViewControler from a button in the Popover. In addition I want it to transfer the data back to the main view. I have it working for a modalViewController but not f...