dimanche 29 novembre 2015

Should I be using IEquatable to ease testing of factories?

I often work with classes that represent entities produced from a factory. To enable easy testing of my factories easily I usually implement IEquatable<T>, whilst also overriding GetHashCode and Equals (as suggested by the MSDN).

For example; take the following entity class which is simplified for example purposes. Typically my classes have a bunch more properties. Occasionally there is a also collection, which in the Equals method I check using SequenceEqual.

public class Product : IEquatable<Product>
{
    public string Name
    {
        get;
        private set;
    }

    public Product(string name)
    {
        Name = name;
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
        {
            return false;
        }

        Product product = obj as Product;

        if (product == null)
        {
            return false;
        }
        else
        {
            return Equals(product);
        }
    }

    public bool Equals(Product other)
    {
        return Name == other.Name;
    }

    public override int GetHashCode()
    {
        return Name.GetHashCode();
    }
}

This means I can then do simple unit tests like so (assuming the constructor is tested elsewhere).

[TestMethod]
public void TestFactory()
{
    Product expected = new Product("James");

    Product actual = ProductFactory.BuildJames();

    Assert.AreEqual(expected, actual);
}

However this raises a number of questions.

  1. GetHashCode isn't actually used but I've spent time implementing it.
  2. I rarely actually want to use Equals in my actual application beyond testing.
  3. I spend more time writing more tests to ensure the Equals actually works correctly.
  4. I now have another three methods to maintain, e.g. add a property to the class, update methods.

But, this does give me a very neat TestMethod.

Is this an appropriate use of IEquatable, or should I take another approach?

Aucun commentaire:

Enregistrer un commentaire