Although this question is aging and the answer has already been put, I feel that I have a good solution that simplifies and reads things. In the end, it allows us to write tests for preconditions as simple as:
[Test] public void Test() { Assert.That(FailingPrecondition, Violates.Precondition); } public void FailingPrecondition() { Contracts.Require(false); }
Ok, so the idea is to provide the Code Contracts rewriter with its own class of contract runtime. This can be configured in the assembly properties in the section "Methods of user rewriting" (see Section 7.7 of the User Guide for Contract Contracts):

Remember to also check Call-site Requires Checking !
A custom class looks something like this:
public static class TestFailureMethods { public static void Requires(bool condition, string userMessage, string conditionText) { if (!condition) { throw new PreconditionException(userMessage, conditionText); } } public static void Requires<TException>(bool condition, string userMessage, string conditionText) where TException : Exception { if (!condition) { throw new PreconditionException(userMessage, conditionText, typeof(TException)); } } }
Using the custom class PreconditionException (there is nothing unusual in it!). In addition, we add a small helper class:
public static class Violates { public static ExactTypeConstraint Precondition => Throws.TypeOf<PreconditionException>(); }
This allows us to write simple, readable pre-condition tests, as shown above.
Mikkel R. Lund Jan 16 '16 at 20:02 2016-01-16 20:02
source share