Assert.AreEqual fails with the same type

I am testing two objects (and their collection), but it fails, although they are of the same type:

enter image description here

I did some research, and possibly because of the links, which may be different. However, its still the same type, and I don’t know which Assert method to use. (The CollectionAssert.AreEquivalent also doesn't work).

Edited

I am also trying to check if the values ​​of each field are the same, in this case, should I do Assert.AreEqual for each field?

- thanks, all the answers were helpful.

0
source share
4 answers

If you want to compare the values ​​for your dto objects, you need to override the Equals and GetHashCode methods.

For example, for a class:

 public class DTOPersona { public string Name { get; set; } public string Address { get; set; } } 

If you think that two objects of the DTOPersona class with the same name (but not an address) are equivalent objects (i.e. the same person), your code might look something like this:

 public class DTOPersona { public string Name { get; set; } public string Address { get; set; } protected bool Equals(DTOPersona other) { return string.Equals(Name, other.Name); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return Equals((DTOPersona) obj); } public override int GetHashCode() { return (Name != null ? Name.GetHashCode() : 0); } } 
+2
source

You must compare the type of object. As you correctly determined, the contents of an object may be different, and therefore they cannot be considered equal.

Try something like

Assert.AreEqual(typeof(ObjectA), typeof(ObjectB))

+2
source

Assert.AreEqual verifies that two objects are the same, not just one type. To do this, follow these steps:

 Assert.AreEqual(A.GetType(), B.GetType()); 
+2
source

Without adding some comparison logic, you won’t be able to find out if your instance of the class matches the data point with another.

To check if all fields have the same value, you can override Object.GetHashCode and Object.Equals .

Working with a field comparison field will also work.

0
source

All Articles