Noah Blumenthal's Blog

May 8, 2009

Checking equalities of object properties in NUnit

Filed under: Uncategorized — noahblu @ 4:59 pm

I’m retrieving some information from a DB and I wanted to check not only that two objects are equal (which might mean that their persistance ID is the same) but that their properties are equal too.  I wrote the following code to do this.  It’s pretty simple and probably isn’t going to do everything I need down the line, but for the test case at hand it worked well.  Feel free to use it but if you improve it I’d love to hear about it.

public static void PropertiesAreEqual(object o1, object o2)
     Type o1Type = o1.GetType();
     Assert.IsInstanceOfType(o1.GetType(), o2);
     System.Reflection.PropertyInfo[] o1Properties = o1Type.GetProperties();
     Type o2Type = o2.GetType();
     foreach (System.Reflection.PropertyInfo prop in o1Properties)
         Console.WriteLine("Checking... " + prop.Name);
         object o1Value = prop.GetValue(o1, null);
         object o2Value = o2Type.GetProperty(prop.Name).GetValue(o2, null);
         Assert.AreEqual(o1Value, o2Value);

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at

%d bloggers like this: