Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Junit4: Exception testing not working, insists on try-catch block:

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{

    }
like image 819
NullVoxPopuli Avatar asked Feb 26 '23 03:02

NullVoxPopuli


2 Answers

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.

like image 169
Tomasz Nurkiewicz Avatar answered May 01 '23 05:05

Tomasz Nurkiewicz


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).

like image 44
Victor Sorokin Avatar answered May 01 '23 03:05

Victor Sorokin