8

Is there an equivalent to NUnit's ExpectedException or Assert.Throws<> in jUnit?

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
ripper234
  • 222,824
  • 274
  • 634
  • 905

3 Answers3

12

You might also consider taking a look at the ExpectedException class which provides richer exception matching.

https://github.com/junit-team/junit/wiki/Exception-testing

Not only you can match the exception class but also you can apply custom matchers to its message.

Tim
  • 19,793
  • 8
  • 70
  • 95
Maciej Biłas
  • 1,966
  • 2
  • 18
  • 20
7

junit4:

@Test(expected = org.dom4j.DocumentException.class)
void shouldThrowException() {
    getFile(null);
}

junit3:

void testShouldThrowException() {
    try {
      getFile(null);
      fail("Expected Exception DocumentException");
    } catch(DocumentException e) {}
}
Jay Prall
  • 5,295
  • 5
  • 49
  • 79
Tim
  • 19,793
  • 8
  • 70
  • 95
  • I have updated this answer to include a way to do this in jUnit3 – Jay Prall Apr 01 '12 at 17:31
  • The good thing about the "JUnit3" approach is that you can then write one exception-test-case per line, whereas you need five lines for each with the "JUnit4" approach. See my answer for more information: http://stackoverflow.com/a/15385613/974531 – Rok Strniša Mar 13 '13 at 12:40
  • Actually the answer using `ExpectedException` by @Maciej is better: http://stackoverflow.com/a/4265441/53444 – Tim Mar 13 '13 at 16:32
2

If you are using Groovy for your junit tests you can use shouldFail.

Here is an example using junit3 style:

void testShouldThrowException() {
    def message = shouldFail(DocumentException) {
        documentService.getFile(null)
    }
    assert message == 'Document could not be saved because it ate the homework.'
}
Jay Prall
  • 5,295
  • 5
  • 49
  • 79