Lucas Campos
Jul 25, 2017 · 1 min read

JUnit — Exception Testing

Last week I was writing some test cases and one of them seemed to be wrong. Here it is:

@Test public void should_get_data_exception() { 
try {
myService.doSomething();
Assert.fail("Something is not wrong?!");
} catch (DataException ex) {
Assert.assertSame(ex.getMessage(), “Something is wrong”);
}
}

That Assert.fail() is looking like a dead code, isn’t it? So I found another way to do the same thing:

@Test(expected=DataException.class) 
public void should_get_data_exception() {
diffService.doSomething();
}

This is a little bit shorter and concise, but… is the other one right or wrong?

Both are right and here is my point of view:

  • That Assert.fail() should be a dead code indeed, but it says to your code that if it hits that line, your test should fail (you are expecting one error, isn’t you?);
  • The first approach should be used when you know the exception you are waiting for and the message, the status code, anything else besides only the exception (it is more specific);
  • The second one should be used when you only know the exception you are expecting and nothing else (it is more general).

Does it make sense to you? Do you have something to share? Let me know in the comments!

For more info, read it.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade