NMock: Delegating Constraint

time to read 4 min | 708 words

I love NMock, it's a good framework and it allows you to do so many nice things so easily. It's the single library that I know of whose documentation is a single page, and it's both accurate and useful.

One of the nice things in NMock is the ability to define expectations and constraints. So you can say:

mockObj.Expect("MethodName"new And(new IsTypeOf(typeof(IList), new PropertyIs("Count",1));

To check that this is an IList with a single element. Sometimes, however, you need more, and often enough it's a one off thing. For those cases, I build the DelegatingConstraint:

public class DelegatingConstraint : BaseConstraint 
 {
  private readonly CheckValue checkValue;
  private readonly string message;
  public delegate bool CheckValue(object val);
  public delegate string ReturnMessage(object val);
  public DelegatingConstraint(CheckValue checkValue, string message)
  {
   if(checkValue==null)
    throw new ArgumentNullException("checkValue");
   if(message==null)
    throw new ArgumentNullException("message");
   this.checkValue = checkValue;
   this.message = message;
  }
  public override bool Eval(object val)
  {
   return checkValue(val);
  }
  
  public override string Message
  {
   get
   {
    return message;
   }
  }
 }

Here is how you would use it in .Net 1.1:

DelegatingConstraint dl = new DelegatingConstraint(new DelegatingConstraint.CheckValue(MyConstraint),"Failed to validate on my constraint"));
mockObj.Expect("MethodName",dl);
...
public bool MyConstraint(object val)
{
   //Complex bussiness logic to validate that the correct object was sent goes here
}

It's simpler in .Net 2.0, of course, but I'm not working with that yet.

More interesting than validation, though, is the possiblity to modify the value that you get, so you simulate a method modifying the sent object*.

* Beware Of Abuse.

[Listening to: לשם - מירי מסיקה - Heralds, Harpers, & Havoc(04:02)]