If you are not familiar with the Code Contracts library which is coming out of Microsoft R&D labs, you need to check this pretty cool little library out. As of Vs2010/.Net 4.0 this library will be making the jump out of the R&D labs.
Over the next few blog posts we will be taking a look at the topics below.
In this post we are going to take a look at how you can setup your unit tests to handle violations from your contracts. If you do not provide any additional support in your code and you violate a contract at test time you will see a dialog like the one below:
The problem with having a dialog like this appear during your test runs should be apparent. Any type of dialog will cause any automated build/test system to pause and wait until there is some user interaction, this is BAD.
The good news is that resolving this issue is actually simple and can be done with a few lines of code. All we need to do is hookup the event listener which the contracts library provides and trap for the violation. The code below shows us how to do this.
private bool _contractViolationHandled;
[SetUp]
public void Setup()
{
Contract.ContractFailed += (sender, o) =>
{
o.SetHandled();
_contractViolationHandled = true;
};
}
[TearDown]
public void TearDown()
{
_contractViolationHandled = false;
}
As you can see from the code above, wiring to handle the violations is simple. But we should point out a few lines to pay attention to.
- o.SetHandled(); – If you do not set this you will still be able to handle the error, but it will continue to bubble up and you will still get the dialog
- [TearDown] – because we are setting a global variable in the setup, we MUST rest that value other wise you may get false errors in future test runs.
There you go, if you need to trap hand handle contract violations in your unit tests, you can utilize the technique above to avoid getting the violations dialog.
Till next time,
Posted
06-13-2009 9:46 AM
by
Derik Whittaker