0

I'm using Code Contracts in my C# application, together with unit tests. When I ask for the code coverage results of the unit tests, lines containing code contracts are reported as "not covered".

Lets take for example a method that has 2 parameters:

void MyMethod(object param1, object param2) {
    Contract.Requires<ArgumentNullException>(param1 != null);
    Contract.Requires<ArgumentNullException>(param2 != null);

    // Other stuff covered explicitly by unit tests
}

Since the contracts fail if the conditions aren't met, shouldn't the code coverage tool report that the two parameters are covered?

For my understanding, code covered by contracts doesn't need to be unit tested again. Is this correct?

drl
  • 811
  • 2
  • 11
  • 21
  • 1
    Have a look here http://stackoverflow.com/questions/1383535/net-4-0-code-contracts-how-will-they-affect-unit-testing?rq=1 – Alex Feb 04 '14 at 14:44
  • Thanks for the link! I think this means I'll have to test exception throwing via unit tests, for example check if `MyMethod(null, null)` actually throws `ArgumentNullException`. This would be less than ideal though, since Contracts have guaranteed functionality. Can someone confirm this is the case? – drl Feb 04 '14 at 17:14

1 Answers1

0

So, you are technically correct that Code Contracts will throw an ArgumentNullException if any one of your arguments are null.

However, it would still be a good idea to unit test your preconditions. It's not so much to ensure that Code Contracts is working correctly—it does! But it's to ensure that you actually specified the right contract!

I am saying this from personal experience. I was writing a blog post on Code Contracts and unit testing. And while writing the sample code, I stated a precondition on a method. I ran the unit tests and a few tests failed. I was a bit taken aback. What happened? Well, silly me, I reversed the Boolean condition I wanted to enforce. Oops. Thanks to unit tests, though, this was caught and easily corrected.

Also, Code Contracts is not only about guaranteeing that parameters don't come in null (in your example). Code Contracts also function as a form of communication to clients of your code. They tell consumers of your library that, if they meet the stated preconditions, you guarantee that the method will execute successfully and satisfy any object invariants and/or stated method postconditions.

While Code Contracts can go a long way in helping you to write code that doesn't fail, it's not a silver bullet. It can't catch all logic errors (Code Contracts won't help you avoid infinite loops, for example). So, unit tests are still very much an important part of the development process even when using Code Contracts.

fourpastmidnight
  • 4,032
  • 1
  • 35
  • 48