简体   繁体   中英

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{

    }

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

Is it possible you have other code in the test method that throws a different exception?

For example...

@Test(expected= XMLClientNotFoind.class)
public void testGetClientFromIP() throws XMLClientNotFound{

    thisMethodThrows_ExceptionX();

    assertEquals(c, sax.getClientFromIP("101.0.2.01"));
} 

In the above case the compiler would complain because you are not handling ExceptionX. You would either have to surround with try/catch or say throws ExceptionX in test method signature as well.

In general it is a good idea to test one thing in a test method. I do not understand the assertion if you are expecting the method to throw an exception; there is nothing to assert since it is not going to return anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM