ExpectedException in jUnit?
Asked Answered
R

3

8

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

Roaring answered 27/6, 2009 at 11:35 Comment(0)
K
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) {}
}
Karr answered 27/6, 2009 at 11:40 Comment(3)
I have updated this answer to include a way to do this in jUnit3Lansquenet
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: https://mcmap.net/q/1256370/-expectedexception-in-junitSherysherye
Actually the answer using ExpectedException by @Maciej is better: https://mcmap.net/q/1256370/-expectedexception-in-junitKarr
N
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.

Natalee answered 24/11, 2010 at 9:53 Comment(0)
K
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) {}
}
Karr answered 27/6, 2009 at 11:40 Comment(3)
I have updated this answer to include a way to do this in jUnit3Lansquenet
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: https://mcmap.net/q/1256370/-expectedexception-in-junitSherysherye
Actually the answer using ExpectedException by @Maciej is better: https://mcmap.net/q/1256370/-expectedexception-in-junitKarr
L
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.'
}
Lansquenet answered 29/3, 2012 at 23:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.