«

»

Mar
26

Achieving 100% code coverage when using NUnit and NCover

Something that has always annoyed me when trying to get 100% code coverage when testing a method that throws an expected exception, is that it exits the method before getting to the end of it (obviously).

An illustration will aid what I’m talking about…

With the above setup, calling repository.GetProjects() throws an InvalidOperationException, as projects are scoped to a company. This is the desired behaviour of the repository class.

However, as you can see, the last brace of the NUnit unit test never gets run, giving you less than 100% code coverage (according to NCover).

This skews your stats of your test suite, making it look like you have untested code. As you can see, that is not the case.

However, today I found a new way to test for expected exceptions in your code AND get 100% code coverage!

NUnit comes with an awesome little method called Assert.Throws().

This allows you to to test a method call which you expect to throw an exception, and carry on with the rest of your unit test.

Here’s the same unit test, rewritten using Assert.Throws():

As you can see, just remove the ExpectedException attribute at the top of the unit test, and let Assert.Throws() handle the rest.

Perfect! 100% code coverage on expected exceptions, no more skewed unit test results.

I hope this helps you with your testing stats too.

1 comment

  1. raffaeu says:

    Thanks man, It works like a charm and I didn’t event think about it. If you decorate the method with [ExpectedException] it doesn’t return 100%, but with Assert.Throws it does!!
    :-)

Leave a Reply

Your email address will not be published.


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>