Alberto Martín
Alberto Martín

Reputation: 119

How can I override the Equals method for object with DateTime fields or properties

I am writing test unit for a method that returns an object. I create an expected object and compare it

    public class Model
    {
        public int Id { get; set; }
        public string Editor { get; set; }
        public DateTime Edited { get; set; } = DateTime.Now;

        public override bool Equals(object obj)
        {
            var myObj = obj as Model;
            if (myObj == null)
                return false;
            return myObj.Id == Id &&
                myObj.Editor == Editor &&
                myObj.Edited == Edited;
        }
    }

    public void MyTest()
    {
        Model expected = new() { Id = 1, Editor = "Me"};
        Model result = cut.getModel();
        Assert.AreEqual(expected, result);
    }

Equals compares Id and Editor but it is always false for the Edited property.

How can I compare instances of this object? Should I Ignore DateTimes fields and properties in the Equals method?

First proposal:

    public void MySecondTest()
    {
        Model expected = new() { Id = 1, Editor = "Me"};
        Model result = cut.getModel();
        expected.Edited = result.Edited = Now;
        Assert.AreEqual(expected, result);
    }

Upvotes: -2

Views: 815

Answers (1)

Cozmin
Cozmin

Reputation: 66

The issue here is with the "Edited" property that is assigned to "DateTime.Now" which is a different value everytime you create an object. Try assigning an exact value:

public class Model
{
    public int Id { get; set; }
    public string Editor { get; set; }
    public DateTime Edited { get; set; } = new DateTime(2022,10,28,16,0,0);

    public override bool Equals(object obj)
    {
        var myObj = obj as Model;
        if (myObj == null)
            return false;
        return myObj.Id == Id &&
            myObj.Editor == Editor &&
            myObj.Edited == Edited;
    }
}

Now if you do:

Model model1 = new Model() { Id = 1, Editor = "editor1" };
Model model2 = new Model() { Id = 1, Editor = "editor1"};

model1.Equals(model2) //should be true

Upvotes: 0

Related Questions