Geeks With Blogs
Denis Pitcher Denis Pitcher's Tech Blog

In trying to comparing complex objects to confirm a unit test, I thought rather than going through the hassle of trying to implement IComparable or overriding .Equals that perhaps reflection would be a better means.

A quick google search turned up some useful code that compares via reflection.

This was close to what I wanted but I thought it’d be better to have it available as an extension method and I needed it in vb.net (excuse the horror) so this is what I came up with:

    <System.Runtime.CompilerServices.Extension()> _
    Public Function Compare(Of T)(ByVal x As T, ByVal y As T) As Boolean
        Dim type As Type = GetType(T)
        Dim properties As PropertyInfo() = type.GetProperties()
        Dim fields As FieldInfo() = type.GetFields()
        Dim compareValue As Int16 = 0

        For Each [property] As PropertyInfo In properties
            Dim valx As IComparable = TryCast([property].GetValue(x, Nothing), IComparable)
            If valx Is Nothing Then
                Continue For
            End If
            Dim valy As Object = [property].GetValue(y, Nothing)
            compareValue = valx.CompareTo(valy)
            If compareValue <> 0 Then
                Return False
            End If
        Next
        For Each field As FieldInfo In fields
            Dim valx As IComparable = TryCast(field.GetValue(x), IComparable)
            If valx Is Nothing Then
                Continue For
            End If
            Dim valy As Object = field.GetValue(y)
            compareValue = valx.CompareTo(valy)
            If compareValue <> 0 Then
                Return False
            End If
        Next

        Return (compareValue = 0)
    End Function

 

Calling it then became a simple

Assert.IsTrue(ObjA.Compare(ObjB));
Posted on Thursday, November 3, 2011 3:40 PM | Back to top


Comments on this post: Comparison extension method for unit testing

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


Copyright © Denis Pitcher | Powered by: GeeksWithBlogs.net