Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asserting exceptions in Java, how? [duplicate]

This might be a conceptually stupid question, but it also might not and since I am still a student I think I should I have no problem asking.

Imagine you have a method that if given certain conditions it will throw an NumberFormatException. I want to write a Unit Test to see if the exception is being correctly thorwn. How can I achieve this?

P.S. I am using JUnit to write the Unit Tests.

Thanks.

like image 500
nunos Avatar asked Oct 28 '10 21:10

nunos


People also ask

Can you catch the same exception twice in Java?

Java does not allow us to catch the exception twice, so we got compile-rime error at //1 .

How do you catch an assertion exception?

In order to catch the assertion error, we need to declare the assertion statement in the try block with the second expression being the message to be displayed and catch the assertion error in the catch block.

Can you throw multiple exceptions?

You can't throw two exceptions. I.e. you can't do something like: try { throw new IllegalArgumentException(), new NullPointerException(); } catch (IllegalArgumentException iae) { // ... } catch (NullPointerException npe) { // ... }


3 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)
}
like image 68
Michael D Avatar answered Oct 03 '22 00:10

Michael D


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.

like image 37
Feanor Avatar answered Oct 02 '22 22:10

Feanor


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

like image 30
NamshubWriter Avatar answered Oct 02 '22 22:10

NamshubWriter