简体   繁体   中英

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://docs.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.

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

Yes, it appears possible in Visual Studio >=2017 or using ReSharper:

https://stackoverflow.com/a/48441971

https://docs.microsoft.com/en-us/visualstudio/ide/reference/generate-equals-gethashcode-methods?view=vs-2017

This would still be time consuming for 1000+ classes. You might look into Visual Studio's APIs for plugin development to see if you could programmatically trigger this option for a whole list of files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM