My Test: this is where it underlines the stuff after sax. and insists that I have a try-catch block.... but the internet says that the proper way to test for exception is @Test(expected=IllegalArgumentException.class)
@Test(expected= XMLClientNotFoind.class)
public void testGetClientFromIP() throws XMLClientNotFound{
...
assertEquals(c, sax.getClientFromIP("101.0.2.01"));
}
And the method, getClientFromIP is here:
public Client getClientFromIP(String ip) throws XMLClientNotFound {
...
throw new XMLClientNotFound();
}
And my exception:
public class XMLClientNotFound extends Exception{
}
First of all:
@Test(expected=IllegalArgumentException.class)
should not be considered as a proper way, especially with such a generic exception. The reason is that you have no control over which statement in your test method actually threw the exception. Also you can't make any assertions on the message label, cause, etc.
Using try-catch
precisely surrounding a line that is suppose to throw an exception is the right way to go:
try {
shouldThrow()
fail("Expected exception");
} catch(XMLClientNotFound e) {
assertThat(e).hasMessage("Expected message"); //FEST-Assert syntax
}
You might also try JUnit @Rule
that I wrote some time ago to make your test more readable.
You still need to define throws
clause for checked exceptions. @Test(expected=...)
part just says JUnit that you expect your test case to throw that exception(s).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With