Home > Enterprise >  While unit testing if an exception is being thrown, how can I know if the exception was thrown due t
While unit testing if an exception is being thrown, how can I know if the exception was thrown due t

Time:10-13

TL;DR version:

How should I known if my method is throwing an exception because of the error scenario that I configured and not because of another error? Also, should I always configure everything in order to test if an exception is being thrown, or only configuring what is used to the point where the exception is thrown is enough?

Long version:

I have a class, MyClass, which has a method called foo. The method foo calls an API that returns an object indicating if the operation succeded. If the object returned by the API indicates an error, the foo method should throw an unchecked exception.

In order to test if foo is throwing the exception, I'm mocking the API, so that it always indicates a fail. The foo method is working as expected, throwing an exception.

It is true, however, that other things can make foo throw exceptions. For instance, if the API succeds but other dependency of fool fails, fool will and should throw an excpetion.

Because of that, in order to test if foo is throwing an exception as results of a fail in the API, I need to mock every other dependency that foo has. Because of that, the unit test that tests if foo throws an exception when the API fails gets too big. This is also true for every other test involving exceptions.

The worst part is that, at the end of the day, I'm always questioning, is it throwing an exception because the API failed, or because there's another error happening?

The solution I can think is creating exception for every possible case of failure, like "HiImFooAndTheApiThatICalledFailed_Exception". I'm not sure if this is a reaonable approach though. Other solution is testing the exception's message, but I think this is bad because I would be limiting message to be static.

CodePudding user response:

You can mock other dependency and check that no methods where called. So if you get exception you will be sure it is from your code.

If you code can throw exception in several different scenarios you test them all separately.

You don't need to worry about which piece of your code thrown exception, only that correct exception was thrown.

As long as you have test for all scenarios you can be reasonably sure you code is fine. Just treat it as black box. If all inputs give you expected outputs it doesn't matter how it happens.

  • Related