Why does Assert.AreEqual (x, y) fail, but Assert.AreEqual (y, x) does not?

Consider this structure:

public struct MyNumber
{
    private readonly int _value;

    public MyNumber(int myNumber)
    {
        _value = myNumber;
    }

    public int Value
    {
        get { return _value; }
    }

    public override bool Equals(object obj)
    {
        if (obj is MyNumber)
            return this == (MyNumber) obj;

        if (obj is int)
            return Value == (int)obj;

        return false;
    }

    public override string ToString()
    {
        return Value.ToString();
    }

    public static implicit operator int(MyNumber myNumber)
    {
        return myNumber.Value;
    }

    public static implicit operator MyNumber(int myNumber)
    {
        return new MyNumber(myNumber);
    }
}

When I do this in unit test:

Assert.AreEqual(new MyNumber(123), 123);

He is green.

But this test fails:

Assert.AreEqual(123, new MyNumber(123));

Why is this so? I assume, because the int class defines equality, whereas in the first case, my class defines it. But my class is implicitly converted to int, so should this not help?

How can I get Assert.AreEqual to work in both directions? By the way, I use MSTest.

Update

Implementation IEquatable<int>or IComparable<int>does not help.

+4
source share
3 answers

MyNumber.Equals, , , Int32 MyNumber.

Int32.Equals, , MyNumber, Int32 .

unit test , , Int32 . , . Int32.Equals, , . , unit test, :

Assert.AreEqual(123, (int) new MyNumber(123));
Assert.AreEqual((MyNumber) 123, new MyNumber(123));

, implicit, Assert.AreEquals, Object, , .

- MyNumber.Equals , , . MyNumber(123) equals Int32(123) , Int32(123) equals MyNumber(123) . , ints MyNumber.Equals , . , .

+6

Object.Equals:

Equals (Object). x, y z , null.

  • ...

  • x.Equals(y) , y.Equals(x).

Equals . ((object)x).Equals(123) , ((object)123).Equals(x), x null, , .

, , , , , . , .

, , , , .

+2

IComparable<int> MyNumber :

    public int CompareTo(int other)
    {
        return other.CompareTo(Value);
    }

This will ensure that all statements work as expected, for example:

    Assert.AreEqual(new MyNumber(123), 123);
    Assert.AreEqual(123, new MyNumber(123));
    Assert.Greater(124, new MyNumber(123));
    Assert.Less(124, new MyNumber(125));
0
source

All Articles