davy
davy

Reputation: 4552

Best place to override Equals and GetHashcode methods only required for testing in C#

I have the need to override Equals() and GetHashCode() so that I can compare two objects of the same class in my unit tests.

Suppose I have the class: MyClass in production that currently has no special requirement for the above methods to be overridden.

However, in my tests I want to compare them using an overridden Equals. Should I:

  1. implement the methods directly in MyClass

  2. create a derived class from MyClass that holds the overrides, then in my tests cast the instances of MyClass appropriately:

    // get instance of expected MyClass
    // get instance of actual MyClass
    Assert.AreEqual((TestMyClass)expected, (TestMyClass)actual);

I'm leaning towards option 2 as I think it keeps the production code cleaner. It would also allow for a business logic specific override in the future directly on MyClass that might do it in different way from what I do in the tests if that makes sense.

I guess the downside is that the tests and the test project are made more complex.

What is the preferred approach?

Upvotes: 2

Views: 125

Answers (4)

Bharathi
Bharathi

Reputation: 1

Create an extension method and use it within the test project...

Upvotes: 0

Matt Nolan
Matt Nolan

Reputation: 123

I'd go for the derived TestMyClass option to keep the production code simpler. However I don't believe you'd be able to cast your MyClass objects to TestMyClass objects, instead you'll most likely need to create new instances of TestMyClass with a constructor that takes a MyClass as a parameter

Upvotes: 0

Peter
Peter

Reputation: 27944

You have a thirth option, implement a custom assert where you preforms the equals logic you want.

Option 1 adds code to your class which is not needed for your business logic, however it may add new bugs. Think about a linq operation, which uses a equal and hashcode. So your class will have a dirrent behavour. Option 2, is a lot of work. And you will have a maintance issue in your unit tests. Besides that you will test different class as your production code. You may have perfectly working code under test, and not working code in production.

Upvotes: 3

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38478

I would suggest implementing IEqualityComparer<T> interface in your test project. .NET also notices this interface for custom equality comparisons in some collection classes and LINQ.

Upvotes: 3

Related Questions