Archive, C#, Software Design

Testing Software Contracts Using ContractTest

Contracts, both explicit and implied, are key in designing a working software system. An example of an explicit contract in C# would be the implementation of an interface, while an implied contract would be something along the lines of all business objects have default constructors. Contracts of both types are critical to the success of a software system, but how do you test for and enforce these contracts?

Explicit contracts are often enforced by the compiler and are not nearly as fragile as implied contracts. Using the ContractTest testing framework you can write test cases for many common implied contracts. You can incorporate ContractTest assertions directly into your existing unit tests. For the following examples I will be using NUnit syntax, but you could use most any other unit test framework.

For example, assume you want to test for the presence of a publicly accessible default constructor on one of your business objects. Such a test using ContractTest would look like.

using ContractTest.Assertions; using NUnit.Framework; using MyNamespace.BusinessObjects; [TestFixture] public class SampleTests{ [Test] public void Test1(){ ContractAssert.Type.HasPublicDefaultConstructor<BizObjectA>(); } } read more