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>(); } }
In the above example BizObjectA is the business object we are testing from our MyNamespace.BusinessObjects fictitious namespace. Assuming the object has a public default constructor the test will pass.
Conversely, had we wanted to test for the absence of a publicly accessible default constructor we could have told NUnit to expect the exception to be thrown from the HasPublicDefaultConstructor method like follows:
[Test] [ExpectedException(typeof(ContractAssertionException))] public void Test2(){ ContractAssert.Type.HasPublicDefaultConstructor<BizObjectA>(); }
Or more tersely:
[Test] public void Test2(){ ContractAssert.Type.LacksPublicDefaultConstructor<BizObjectA>(); }
In addition to testing for default constructors ContractTest also allows assertions on many other parameters often found in implied contracts.