Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nunit: Check that two objects are the same

Tags:

c#

nunit

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?

like image 310
Sachin Kainth Avatar asked Feb 20 '26 06:02

Sachin Kainth


2 Answers

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();
        }
    }
like image 77
Bilal Bashir Avatar answered Feb 22 '26 18:02

Bilal Bashir


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.

like image 34
Dan Avatar answered Feb 22 '26 20:02

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!