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'll have to implement IEquatable<T> for your objects, and then Assert. Equals will work. Assert. Same() compares by reference; it asserts that Obj1 and Obj2 are the same object rather than just looking the same.
Assert. AreEqual() compares references. Usually when comparing lists I compare the count of the items and than some properties of one exact item in the list or directly the item in the list (but again it is the reference).
Assert. Equal(expected.Name, actual.Name); The first example fails due to the way comparison works for reference types. By default, the equality operation for those types will only assert whether the two objects being compared are the same, namely your variables are pointing to the same object within the memory heap.
I had similar issue, but then luckily I am already using
using Newtonsoft.Json;
So I just had to serialize it to json object then compare as string.
var obj1Str = JsonConvert.SerializeObject(obj1); var obj2Str = JsonConvert.SerializeObject(obj2); Assert.Equal(obj1Str, obj2Str );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With