Code contracts are great and I really recommend you use them, but how do they fit into a TDD/BDD flow of development?

When you do test first development you really want to write your unit test and then use the code contracts to satisfy those tests and hit some of those boundary conditions.  You could also use Pex, but Pex is an “after the code is written” tool and really only fits in as a “did I cover all the edges” tool.

The latest versions of code contracts have removed the ability to catch the exception thrown by the contracts when assertions are off, so you can just do a plan Assert.Throws() check.  instead you need to rely on xUnit’s ability to catch an assert failure in a method call and wrap that into it’s own internal exception class – the Xunit.Sdk.TraceAssertException.

First – make sure you’ve got run time checking of contracts set to throw Assert failures in the project properties:

image

Then you can just do code like the following:

public class ContractTestClass
{
[Fact]
public void ShouldPassRequires()
{
Assert.DoesNotThrow(() => AClass.PositiveInt(1));
}

[Fact]
public void ShouldPassEnsures()
{
Assert.DoesNotThrow(() => AClass.AnotherPositiveInt(3));
}

[Fact]
public void ShouldFailRequires()
{
Assert.Throws<TraceAssertException>(() => AClass.PositiveInt(-1));
}

[Fact]
public void ShouldFailEnsures()
{
Assert.Throws<TraceAssertException>(() => AClass.AnotherPositiveInt(-2));
}
}

public class AClass
{
public static void PositiveInt(int i)
{
Contract.Requires(i >= 0);
}

public static int AnotherPositiveInt(int i)
{
Contract.Ensures(Contract.Result<int>() >= 0);
return i;
}
}