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 specifi开发者_运维知识库cally 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.
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.
精彩评论