NUnit doesn't work well with Assert.AreEqual

Posted by stasal on Stack Overflow See other posts from Stack Overflow or by stasal
Published on 2009-09-03T13:17:25Z Indexed on 2010/05/23 21:11 UTC
Read the original article Hit count: 254

Filed under:
|
|

Hi! I'm new to unit-testing and NUit in particular. I'm just typing some examples from the book which refers to Java and JUnit. But I'm using C# instead.

The problem is: I've got a class with overriden methods such as Equals() and GetHashCode(), but when I am trying to compare two objects of this class with Assert.AreEqual() my code is not called, so I get an exception.

Assert.True(MyClass.Equals(MyClass2)) does work well. But I don't wanna use this construction instead of Assert.AreEqual(). Where the problem can be?

Here is the class:

public class Money
{
    public int amount;
    protected string currency;

    public Money(int amount, string currency)
    {
        this.amount = amount;
        this.currency = currency;
    }

    public new bool Equals(object obj)
    {
        if (obj == null)
            return false;

        Money money = (Money)obj;
        return (amount == money.amount) 
                && (Currency().Equals(money.Currency()));
    }

    public new int GetHashCode()
    {
        return (string.Format("{0}{1}", amount, currency)).GetHashCode();
    }

    public static Money Dollar(int amount)
    {
        return new Money(amount, "USD");
    }
    public static Money Franc(int amount)
    {
        return new Money(amount, "CHF");
    }

    public Money Times(int multiplier)
    {
        return new Money(amount * multiplier, currency);
    }

    public string Currency()
    {
        return currency;
    }
}

And the test method itself:

[TestFixture]
public class DollarTest
{
    [Test]
    public void TestMultiplication()
    {
        Money five = Money.Dollar(5);
        Assert.True(Money.Dollar(10).Equals(five.Times(2)));  // ok
        Assert.AreEqual(Money.Dollar(10), five.Times(2));     // fails
    }
}

Thanks.

© Stack Overflow or respective owner

Related posts about c#

Related posts about unit-testing