Sachin Kainth Sachin Kainth - 1 month ago 5
C# Question

Nunit: Check that two objects are the same

I have an object

public class Foo
public string A{ get; set; }
public string B{ get; set; }

I am comparing the return value from the SUT when it returns null for A and B like this.

Assert.That(returnValue, Is.EqualTo(new Foo { A = null, B = null}));

This did not work, so I tried

Assert.That(returnValue, Is.SameAs(new Foo { A = null, B = null}));

This didn't work either.

I get a message like

Expected: same as <Namespace+Foo>
But was: <Namespace+Foo>

What am I doing wrong?


From nunit documentation,

When checking the equality of user-defined classes, NUnit makes use of the Equals override on the expected object. If you neglect to override Equals, you can expect failures non-identical objects. In particular, overriding operator== without overriding Equals has no effect.

You can however supply your own comparer to test if the values are equal for the properties.

If the default NUnit or .NET behavior for testing equality doesn't meet your needs, you can supply a comparer of your own through the Using modifier. When used with EqualConstraint, you may supply an IEqualityComparer, IEqualityComparer, IComparer, IComparer; or Comparison as the argument to Using.

Assert.That( myObj1, Is.EqualTo( myObj2 ).Using( myComparer ) );

So in this case your comparer would be

    public class FooComparer : IEqualityComparer
        public bool Equals(Foo x, Foo y)
            if (x.A == y.A && x.B == y.B)
                return true;
            return false;
        public int GetHashCode(Foo inst)
            return inst.GetHashCode();