I’m planning to implement my own set of constraints, and am having some difficulty understanding how to implement the following methods of the Constraint class.
public abstract class Constraint
{
public abstract void WriteDescriptionTo( MessageWriter writer );
public virtual void WriteMessageTo( MessageWriter writer );
public virtual void WriteActualValueTo( MessageWriter writer );
}
The documentation suggests reading the source code to get a good idea on how to use them, but I’ve studied many constraints and haven’t seen much deviation from their implementation — usually WriteDescriptionTo() is the only implemented method.
From my observations:
WriteMessageTo()is called to write the assertion error message to the consoleWriteActualValueTo()formats the value of the actual parameter that is given to the constraint, for writing to the console
However, I don’t understand the purpose of WriteDescriptionTo(), nor understand why it is abstract — especially when overriding WriteMessageTo() suffices.
From looking at the source code, the
WriteDescriptionTomethod is used to write out the expected value of a constraint upon failure. A generic two-line view is used to display failed constraints; the first line containing the expected value and the second line containing the actual value.The
WriteDescriptionTois abstract to force constraints to implement it. The methodWriteActualValueTois used to write the actual value. This is implemented in the baseConstraintclass and marked as virtual. By default, it just outputs the raw actual value, but it being virtual means that each inherited constraint can override it and do something more specific if needed.