Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XUnit Assertion for checking equality of objects

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 
like image 360
inquisitive Avatar asked Jun 21 '12 09:06

inquisitive


People also ask

How do you assert two objects are equal in xUnit?

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.

How do you compare two objects using assert?

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).

How do you assert equal in C#?

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.


1 Answers

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 ); 
like image 153
The Integrator Avatar answered Sep 24 '22 08:09

The Integrator