Over a million developers have joined DZone.

Expected exceptions in unit tests

DZone's Guide to

Expected exceptions in unit tests

Free Resource

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
target.Divide(a, b);


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:

[ExpectedException (typeof(DivideByZeroException))]

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.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}