Search code examples
c#asp.net-core.net-coret4iequatable

Net Core: Code Generation for IEquatable/Equals for Comparing Two Class Models


We scaffolded database from Entity Framework to create class models. We have over 1000 classes. Now we're implementing unit tests, to compare classes inserting an Actual class with Expected class. The following website recommends method below to compare all Members.

Do I have to write this for all my 1000+ classes? Or is there a way to use auto code generate in Visual Studio to create all these IEquatable? Maybe with T4?

https://grantwinney.com/how-to-compare-two-objects-testing-for-equality-in-c/

public class Person : IEquatable<Person> 
{
    public string Name { get; set; }
    public int Age { get; set; }

    public bool Equals(Person other)
    {
        if (ReferenceEquals(other, null))
            return false;

        if (ReferenceEquals(this, other))
            return true;

        return Name.Equals(other.Name) && Age.Equals(other.Age);
    }

https://learn.microsoft.com/en-us/visualstudio/modeling/code-generation-and-t4-text-templates?view=vs-2019

Teamwork Guy answer below is nice, need to way to implement this kind of method for 1000+ classes.


Solution

  • If you are only implementing Equals for test assertions, I would use a library like FluentAssertions to do assertions. The various BeEquivalentTo methods compare object graphs and give detailed error messages (e.g. expected Age to be x but was y) which are often better than what you will get out of implementing your own Equals methods. It integrates with all the major test frameworks out of the box (mstest, nunit, xunit.net).