简体   繁体   中英

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();
        }
    }

Nunit is comparing the two objects objects by reference so it is showing the two objects are not equal. You will have to override the Equals method in your object class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM