Why use Code Contracts?
By providing pre-compiled code contract interfaces other developers can adhere to signatures and also expected behavior. This is specially important due to the Liskov substitution principle.
Dino Esposito wrote a great article on the topic called Code Contracts Preview: Interfaces.
Testing
To test that all the right contracts are in place a test project can be created.
Testing preconditions is possible by catching the exceptions created by those preconditions.
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ModelNegativeBlance()
{
Account acc = new Account()
{
AccountName = "NewAccount",
//0 or positive is expected
Balance = -99,
CreationDate = DateTime.Now
};
}
Testing postconditions is a bit tricky because the exceptions raised by postconditions are not meant to be caught. Therefore plain strings have to be used.
public static class TestHelpers
{
public static string ContractExceptionName = "System.Diagnostics.Contracts.__ContractsRuntime+ContractException";
}
public class RepositoryTests
{
public RepositoryTests()
{
}
[TestMethod]
public void InsertModelWithNoParitionKeyDueToBadRepository()
{
var repo = SetBadRepo();
Account acc = new Account()
{
AccountName = "NewAccount",
Balance = 0,
CreationDate = DateTime.Now
};
try
{
repo.InsertAccount(acc);
}
catch (Exception ex)
{
Assert.AreEqual(TestHelpers.ContractExceptionName, ex.GetType().FullName);
}
}
}