Skip to content Skip to sidebar Skip to footer

Should Unit Test Use 'throws Exception' By Default?

In other words should I append throws Exception to all or most of my unit tests? When you generate a unit test with Android Studio (command N -> Test Method) it adds throw Excep

Solution 1:

I don't think a compelling case could be made for demanding that every test case be declared to throw Exception.

For code which throws specific exceptions (i.e. where the exceptions form part of the pubic contract) you would expect test cases to address those specific exception paths and use of the root Exception could result in assertions being demoted to something simplistic. Similar, perhaps, to testing a method which calculates a number by simply asserting that any number is returned rather than asserting that the correct number is returned.

In addition, for code which throws a checked exception a default statement of throws Exception would mask specific, checked exceptions thrown by the code-under-test. This would deny you a valuable hint or clue when writing your test. For example, the following code ...

publicvoid someMethod throws SomeMethodFailedException {
    ...
}

... might benefit from a test case which explicitly tests the path where SomeMethodFailedException is thrown. If your test cases are not declared by default with throws Exception then the compiler will effectively act as a reminder to you to test for the path where SomeMethodFailedException is thrown.

So, in summary, declaring all tests to throw Exception could (whether intentionally or not) result in your test cases side stepping the exception contract or ignoring exception paths and, generally speaking, neither of those strategies would be desireable.

Of course, the issues described above are not invariable outcomes of declaring with throws Exception since you can have that declaration whilst also testing exception paths but the use of throws Exception on all tests does hint at (and possibly encourage or validate) a test approach which does not treat exception paths as meaningful test scenarios.

If you are concerned that the default template in Android Studio creates a test in this manner then you can change that default or create your own 'test method' shortcut.

Solution 2:

You should not use Exceptions too often in your tests, In fact you should not use them at all ( in most cases).

The unit test is for your functions to make sure that if they are working the way you want !

So you should find a way to test your functions with assertations,which will be much more clear and effective test.

Post a Comment for "Should Unit Test Use 'throws Exception' By Default?"