I am using XUnit framework to test my C# code.
Is there any assert method available in this framework which does the object comparison? My intention is to check for equality of each of the object's public and private member variables.
I tried those alternatives but seldom it works:
1) bool IsEqual = (Obj1 == Obj2)
2) Assert.Same(Obj1, Obj2) which I couldnt understand what happens internally
You need to have a custom comparer to achieve this, when you compare objects otherwise they are checked on the basis of whether they are referring to the same object in memory. To override this behavior you need to override the
Equals
andGetHashCode
method and then you could do:Here is an MSDN page abt overloading Equals method: http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
Also apt the comment on the question: What's the difference between IEquatable and just overriding Object.Equals()?
There are NuGet packages that do this for you. Here are two examples that I personally use.
DeepEqual:
ExpectedObjects:
I had similar issue, but then luckily I am already using
So I just had to serialize it to json object then compare as string.
I know this is an old question, but since I stumbled upon it I figured I'd weigh in with a new solution that's available (at least in xunit 2.3.1 in a .net Core 2.0 solution).
I'm not sure when it was introduced, but there is now an overloaded form of
.Equal
that accepts an instance ofIEqualityComparer<T>
as the third parameter. You can create a custom comparer in your unit test without polluting your code with it.The following code can be invoked like this:
Assert.Equal(expectedParameters, parameters, new CustomComparer<ParameterValue>());
XUnit natively appears to stop processing a test as soon as a failure is encountered, so throwing a new
EqualException
from within our comparer seems to be in line with how XUnit works out of the box.Edit: I found that comparing the actual and expected values with
!=
was not effective for certain types (I'm sure there's a better explanation involving the difference between reference types and value types, but that's not for today). I updated the code to use the.Equals
method to compare the two values and that seems to work much better.FluentAssertions library has some pretty powerful comparison logic inside.
You can even use this to assert on part of "myObject". However, it might not help you with the private fields.