[Test]
public void testMultiplication()
{
var five=new Dollar(5);
Assert.AreEqual(new Dollar(10), five.times(2));
Assert.AreEqual(new Dollar(15), five.times(3));
}
Dollar class
public class Dollar
{
private int amount;
public Dollar(int amount)
{
this.amount = amount;
}
public Dollar times(int multiplier)
{
return new Dollar(amount * multiplier);
}
public bool equals(Object theObject)
{
Dollar dollar = (Dollar) theObject;
return amount == dollar.amount;
}
}
On line Assert.AreEqual(new Dollar(10), five.times(2)); test fail with error:
Expected: TDDbooks.Dollar
But was: TDDbooks.Dollar
NUnit displays string representation of objects. In order to have handy output, you should override
ToStringmethod ofDollarclass:Now output will be like:
Next problem is dollars comparison. NUnit compare objects by calling
Equalsmethod (notequals, butEquals. Kent Beck uses Java in his examples. In C# we have Pascal naming for methods). Default implementation ofEqualsmethod return true if objects have same reference. But inTimesmethod you create new instance ofDollarclass. In order to fix that, you should changeEqualsmethod implementation to compare amount field.Also notice, that you should use
overridekeyword for overriding base class functionality. And one more thing – when you are overridingEqualsfunctionality, you should overrideGetHashCodemethod. In your case it’s OK to have something like: