I have a class which contains this attributes:
public class Person
{
public long Id { get; set; }
public string Name { get; set; }
public int? IdCountry { get; set; }
public virtual Country Country { get; set; }
public int? IdState { get; set; }
public virtual State State { get; set; }
}
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}
public class State
{
public int Id { get; set; }
public string Name { get; set; }
public int IdCountry { get; set; }
public virtual Country Country { get; set; }
}
In a unit test I create 2 objects with the same values
Person expected = new Person()
{
Name = "blablablbla",
Id = 1
};
Person actual = PessoaFactory.Create(Name: "blablablbla", Id: 1);
Assert.AreEqual<Person>(expected, actual);
But the Assert.AreEqual throws an exception.
Because you need to override Equals
and GetHashCode
:
public override bool Equals(object o)
{
if (!(o is Person)) { return false; }
return ((Person)o).Id == this.Id;
}
public override int GetHashCode()
{
return this.Id;
}
Assert.AreEqual<T>
uses the default comparer for the type. The default comparer for that type is to compare hash codes. The hash codes aren't equal.