Expected exceptions in unit tests
Join the DZone community and get the full member experience.Join For Free
Exceptions can happen in any piece of code. More than that, some of the exceptions can be predicted and tested against. For example, if there is a method performing a division, you can expect that at some point a DivideByZeroException will be triggered.
When using unit tests in .NET, you can specify that a specific exception type is expected vi an attribute. To demonstrate this, I have a sample function:
public int Divide(int a, int b)
return a / b;
It divides two integers, but inside the function itself there is no exception handling and it automatically returns the division value without prior checking. This is a bad way to code something like this, but just to demonstrate the method, it works.
Now, when I create a unit test, I can try creating something like this:
public void DivideTest()
Some target = new Some(); // TODO: Initialize to an appropriate value
int a = 12; // TODO: Initialize to an appropriate value
int b = 0; // TODO: Initialize to an appropriate value
Note that Some is the name of the class that holds the function. If I run this test, it will fail due to the fact that an exception will be thrown – DivideByZeroException.
I can add the following attribute to the test method:
This is a way to tell the test that you as the developer are aware of such an exception. Even if it appears, the test will still pass. With this attribute being set, try running the above function and you will see that the test passes:
If I handle the exception internally, and then define an expected exception, the test will fail, as no exception was thrown, although it is declared in the test. Once you remove the attribute, the test will pass.
I personally wouldn’t recommend over-using this method unless there is a clear need to do so. It is always much better to handle the exceptions in code than let them slide in unit tests. This specific method can mess up some tests if incorrectly used – once it hits an exception, the method will no longer execute. In long term, this might cost an incorrect operation and an eventual problem that will need to be fixed later on.
Opinions expressed by DZone contributors are their own.