views:

137

answers:

2

I have fair amount of knowledge on unit testing. I have been trying to read about code contracts. Does it really help unit testing? Is it over-rated especially when we talk about code-contract helping to do unit testing. I am specifically referring to contracts in .net 4.0. I use nunit for unit testing.

+2  A: 

Yes and No. Unit tests are basically a contract that says, MyMethod() takes X and expects that Y will be a result, and when it doesn't do that, then unit tests fail and you are alerted as the developer of MyMethod() that you broke something inside it. Code contracts do help you write unit tests, because the requirements in the contracts make it easier for you to know the requirements of the unit tests when you write them. However, the true reason for code contracts is not for you, but for other developers using the API that you create. Unit tests let you know proper inputs and outputs, but when you release code into the wild, unit tests aren't released with the .dll. Code contracts give other developers the benefit of knowing, through compile-time contracts and checking, those same requirements. Contracts protect against those developers (me) that have a horrible tendency to not read the method documentation and just start passing in things, so now they will be actively warned through contracts.

Ryan Hayes
But won't that duplicate my logic? I mean, we will have the same logic (pre and post conditions) for contracts and unit testing.
P.K
It will, and from a purist standpoint, it should, since if someone accidentally removes the contract, the unit tests would still verify the logic that you don't want it to do something that it may now do, or vice versa. The contracts can be a guide to writing unit tests, but still aren't a replacement for them.
Ryan Hayes
A: 

No, I don't think that code contracts help you write unit tests. Unit tests define the behavior and constraints of a given action. One of those specifications written in the unit tests might be that arguments to a method cannot be null.

In that case, you still need to write the unit test. The code contract is a way to implement your specification, but not the only way.

In other words, do not assume that using a code contract means that you do not have to write a unit test! If someone changes the code contract or removes it, you will not have a test telling you that that intended specification has failed.

Brian Genisio
I don't think anybody was saying that code contracts should replace unit tests.
David Neale