Is it a good practice to just throw all Exceptions into a JUnit test?

Instead of doing exception handling in my JUnit tests, I simply declare my test methods with ... throws Exception ?

I started to do this, and I see no reason why I should be more specific.

+7
java unit-testing junit junit4
source share
2 answers

The main aspect of unit tests is to help you isolate / resolve errors in your production code as quickly as possible.

In this sense: you are not writing your @Test methods to be called by other methods. You write them so that they are executed by the JUnit framework.

And usually when this test throws an exception; it makes no sense to catch this (if it is not expected, and you want to continue checking this exception).

Thus: not having catch blocks; and instead, adding the potential causes of the drop to your test method signatures is the correct answer in 99.999% of all cases. Or maybe 100%; since I cannot find a good counter example.

But I would be careful if I quickly used throws Exception . You still want your code as specific as possible; so it’s better to go for throws ThatExceptionThatCanReallyBeThrown . And when this list is too long too often ... then you better keep an eye on this side and check if your cast list in your production code needs to be β€œcut off” in some way.

Edit: perhaps the main thing to understand: for each of your tests, you have the expected exactness of what will happen. This method should:

  • Do not throw an exception
  • Throw a specific exception (then you will do the @Test(expected=...) thing
  • Throw a specific exception ... that your test needs to be caught for further verification.
  • Throw an exception ... which will then point to the real β€œerror” condition (because you did not expect this); and in this case, JUnit will catch the exception and report it to you as an unsuccessful test file. (But of course, keep in mind that there is a subtle difference in JUnit with a test error and a test error.)

And just putting throws X, Y on your test method signature is a direct way to address bullets 2 and 4.

+12
source share

In addition to @GhostCat's answer, I want to say - JUnit has a nice feature called Rules . It is well suited for testing exceptions, and perhaps better than @Test(expected=Whatever.class) .

Usage example:

 public class Test { @Rule public final ExpectedException thrown = ExpectedException.none(); private MyService myService; @Before public void setUp() { myService = new MyService (); } @Test public void exceptionTest() throws MyException { thrown.expect(MyException.class); thrown.expectMessage("my description"); myService.create("bad argument"); //throws MyException("my description") } } 
+4
source share

All Articles