AbstractConstraint - inheriting Rhino Mocks objects to override comparisons

As you may have discovered, there are certain objects in .Net are not easily comparable.  For example, if you create two objects of type StringDictionary and add exactly the same keys/values to both and then compare them, it will say they're not equal.  This can be a problem when unit testing.  Here's some sample code in C# that should help you compare the StringDictionary and FileInfo classes using Rhino's AbstractConstraint class.

 

public class StringDictionaryConstraint : AbstractConstraint {

 

   private StringDictionary _Dictionary;

 

   public StringDictionaryConstraint(StringDictionary dictionary) {

 

      _Dictionary = dictionary;

 

   }

 

   public override bool Eval(object obj) {

 

      if (!(obj is StringDictionary)) {

 

         return false;

 

      }

 

      StringDictionary dic = (StringDictionary)obj;

 

      foreach (String key in dic.Keys) {

 

         if (Equals(_Dictionary[key], dic[key]) == false) {

 

            return false;

 

         }

 

      }

 

      return true;

 

   }

 

   public override string Message {

 

      get {

 

         return "String dictionary objects do not match.";

 

      }

 

   }

 

}

 

 

 

public class FileInfoConstraint : AbstractConstraint {

 

   private FileInfo _FileInfo;

 

   public FileInfoConstraint(FileInfo fi) {

 

      _FileInfo = fi;

 

   }

 

   public override bool Eval(object obj) {

 

      if (!(obj is FileInfo)) {

 

         return false;

 

      }

 

      FileInfo f = (FileInfo)obj;

 

      if (f.FullName != _FileInfo.FullName) {

 

         return false;

 

      }

 

      return true;

 

   }

 

   public override string Message {

 

      get {

 

         return "FileInfo objects do not match.";

 

      }

 

   }

 

}

Print | posted on Wednesday, February 21, 2007 8:42 PM

Comments on this post

No comments posted yet.

Your comment:

 (will show your gravatar)
 
Please add 4 and 4 and type the answer here: