Geeks With Blogs

News
The Wrecking Bawl Destructuring query language, one keyword at a time.

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.";

 

      }

 

   }

 

}

Posted on Wednesday, February 21, 2007 8:42 PM all tech stuff , C# | Back to top


Comments on this post: AbstractConstraint - inheriting Rhino Mocks objects to override comparisons

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Alex Bransky | Powered by: GeeksWithBlogs.net