Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

Den works on awesome stuff. He is a sophomore in college, a Microsoft MVP, a Microsoft Student Insider, a technical writer for DZone and a contributing author for Coding4Fun on Channel9. He is maintaining a number of open-source projects on CodePlex and GitHub. Den is a DZone Zone Leader and has posted 388 posts at DZone. You can read more from them at their website. View Full User Profile

Expected exceptions in unit tests

05.25.2010
Email
Views: 3276
  • submit to reddit

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:

[TestMethod()]
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.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)