mardi 5 juillet 2016

NSubstitute, assert on received calls, arguments is compared using object.ReferenceEquals

Please take a look at the following sample:

    public interface IDomainClass
    {
        int A { get; set; }
        void CalledMethod(IDomainClass data);
    }
    public class DomainClass : IDomainClass
    {
        public int A { get; set; }

        public void CalledMethod(IDomainClass data)
        {
            throw new NotImplementedException();
        }
    }

And the following test:

    [Test]
    public void TestSample()
    {
        //Arrange
        IDomainClass testingClass = Substitute.For<IDomainClass>();

        IDomainClass data = new DomainClass() { A = 123, };
        IDomainClass expectedResult = new DomainClass() { A = 123, };

        //Act
        testingClass.CalledMethod(data);

        //Assert
        testingClass.ReceivedWithAnyArgs(1).CalledMethod(null); //ok
        data.ShouldBeEquivalentTo(expectedResult);              //ok
        testingClass.Received(1).CalledMethod(expectedResult);  //fail
    }

The problem is that I don't know how to test the arguments in the received call (CallMethod). As it is, the arguments is compared using object.ReferenceEquals and since I usually don't have control over the delivered data to the method, the objects (data and expectedResult) never references the same object.

However, there is a way to make it work, and that is if I override Equals, like this:

        public override bool Equals(object obj)
        {
            return this.A.Equals((obj as DomainClass).A);
        }
        public override int GetHashCode()
        {
            return this.A.GetHashCode();
        }

This will work, but I don't want to implement Equals to satisfy a test since it will have all kind of other implications not worth mentioning here.

What I want is a comparer doing the same a the second assert line:

data.ShouldBeEquivalentTo(expectedResult);

But this is not supported per default.

So, how do I solve this problem. Thank you.

Aucun commentaire:

Enregistrer un commentaire