Installation

  1. Download the LightContracts DLL
  2. Add a reference to the LightContracts.dll in your .NET project

Usage

Insert a "using LightContracts;" statement in your class files. Write your pre- and postconditions directly in the methods:

// Preconditions
Requires.That(IsInit, "Instance is initialized");
Requires.That(i<max, "{0} is smaller than {1}",i,max);
Requires.IsNotNull(text,"text");

// Postconditions
Ensures.That(IsInit, "Instance is initialized");
Ensures.That(i<max, "{0} is smaller than {1}",i,max);
Ensures.IsNotNull(text,"text");
			
// Check Assertions
Checks.That(IsInit, "Instance is initialized");
Checks.That(i<max, "{0} is smaller than {1}",i,max);
Checks.IsNotNull(text,"text");

The second That() method should be used, when we have a non-constant description string. Only in case of a failing assertion, string.Format() will be used to construct the string. This improves performance, especially, when the assertion is checked very often.

Failing Assertion

All assertions throw an AssertionException in case the condition is not met. The message of the exception has the form:
"<AssertionType> failed. The expectation was '<DescriptionString>', but this is false."

[Test]
public void RequireFalse()
{
    try
    {
        Requires.That(false, "desc");
        Assert.Fail("This code should not be reached.");
    }
    catch(AssertException exception)
    {
        Assert.AreEqual("Precondition failed. The expectation was 'desc', but this is false.", exception.Message);
    }
}

Configuration

  • There is no mechanism to switch on and off the runtime checking of assertions. In my opinion it does not make sense to switch off the runtime checking in production code, because we would recognize errors resulting from a failing assertion much later and without the descriptive assertion message.

Last edited Nov 12, 2009 at 9:37 AM by SvenGrand, version 12

Comments

No comments yet.