views:

158

answers:

1

Hello:

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 console
  • WriteActualValueTo() 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.

+1  A: 

From looking at the source code, the WriteDescriptionTo method 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 WriteDescriptionTo is abstract to force constraints to implement it. The method WriteActualValueTo is used to write the actual value. This is implemented in the base Constraint class 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.

adrianbanks
Thank you for the information Adrian. It sounds like I should override WriteDescriptionTo() AND WriteActualValueTo() if I intend to use the default error formatting. Overriding WriteMessageTo() implies that the default or no-op implementation of the other two methods is sufficient.
Steve Guidi