If I'm using the new Code Contracts Contract.Assert
method, is it possible to make it throw an exception rather than display a dialog box? I want to do this when running unit tests on the build machine.
Asked
Active
Viewed 1,213 times
6

user2864740
- 60,010
- 15
- 145
- 220

Nick Randell
- 17,805
- 18
- 59
- 74
2 Answers
6
Thanks to this post on MSDN forums I've found a possible solution.
namespace QuickGraph.Tests
{
[TestClass]
public class AssemblyContextTest
{
[AssemblyInitialize]
public static void Initialize(TestContext ctx)
{
// avoid contract violation kill the process
Contract.ContractFailed += new EventHandler<ContractFailedEventArgs>(Contract_ContractFailed);
}
static void Contract_ContractFailed(object sender, System.Diagnostics.Contracts.ContractFailedEventArgs e)
{
e.SetHandled();
Assert.Fail("{0}: {1} {2}", e.FailureKind, e.Message, e.Condition);
}
}
}
This appears to work.

Micah Zoltu
- 6,764
- 5
- 44
- 72

Nick Randell
- 17,805
- 18
- 59
- 74
0
According to the documentation:
If your code must throw a particular exception on failure of a precondition, you can use the generic overload of Requires as follows.
Contract.Requires<ArgumentNullException>(x != null, "x");
This is much more simple than the old accepted solution to this problem.

HackSlash
- 4,944
- 2
- 18
- 44