Legacy Documentation. View NUnit 3 Documentation

Custom Constraints (NUnit 2.4)

You can implement your own custom constraints by creating a class that inherits from the Constraint abstract class, which supports performing a test on an actual value and generating appropriate messages. The class includes two abstract methods, which you must override and two virtual methods which may be overridden as needed:

public abstract class Constraint
{
 	...
    public abstract bool Matches( object actual );
    public abstract void WriteDescriptionTo( MessageWriter writer );
    public virtual void WriteMessageTo( MessageWriter writer );
    public virtual void WriteActualValueTo( MessageWriter writer );
	...
}

Your derived class should save the actual argument to Matches in the protected field actual for later use.

The MessageWriter abstract class is implemented in the framework by TextMessageWriter. Examining the source for some of the builtin constraints should give you a good idea of how to use it.