Java: Junit4: Exceptional testing does not work, insists on a try-catch block:

My test: this is where it emphasizes the material after the saxophone. and insists that I have a try-catch block .... but the Internet says that the correct way to check for an 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 getClientFromIP method is here:

  public Client getClientFromIP(String ip) throws XMLClientNotFound { ... throw new XMLClientNotFound(); } 

And my exception is:

  public class XMLClientNotFound extends Exception{ } 
+4
source share
3 answers

Primarily:

 @Test(expected=IllegalArgumentException.class) 

should not be construed as an appropriate method, especially with such a general exception. The reason is that you have no control over which operator in your test method actually threw an exception. Also you cannot make any statements on the message label, reason, etc.

Using try-catch , exactly related to the line that is supposed to throw an exception, is the right way:

 try { shouldThrow() fail("Expected exception"); } catch(XMLClientNotFound e) { assertThat(e).hasMessage("Expected message"); //FEST-Assert syntax } 

You can also try JUnit @Rule , which I wrote a while ago to make your test more readable.

+7
source

You still need to define throws for thrown exceptions. @Test(expected=...) part simply tells JUnit that you expect your test case to throw this exception.

+1
source

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

For instance...

 @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 will complain because you are not handling ExceptionX. You will also have to surround try / catch or say throws ExceptionX in the signature of the test method.

In general, it is recommended to test one thing in the testing method. I do not understand the statement if you expect the method to throw an exception; there is nothing to argue, since he is not going to return anything.

0
source

Source: https://habr.com/ru/post/1338929/


All Articles