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.
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.
Code contracts can be used for things you can't use unit tests (contracts for interfaces). They are applied in inheritance chains (where you can easily make mistakes with manual unit testing). They provide documentation automatically (something unit tests can't do). They can provide runtime checks in production (something unit tests can't do).
On the other hand, contracts only fail when they are excercised, and so without unit tests you have no assurances of code quality (i.e. that all of your code fullfills the various contracts). The two concepts are complimentary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With