Reputation: 73
So I have worked through the Money example in Kent Beck's book Test Driven Development by Example and have been able to get the code to work up until the last test that he writes:
@Test
public void testPlusSameCurrencyReturnsMoney(){
Expression sum = Money.dollar(1).plus(Money.dollar(1));
assertTrue(sum instanceof Money);
}
and here is the function that this calls
public Expression plus(Expression addend) {
return new Sum(this, addend);
}
When I run this, it gives java.lang.AssertionError
, so my question is why is it giving this error and how do I fix it?
Upvotes: 7
Views: 2037
Reputation: 74
Lunivore already answered the question with how to solve the problem, but I think you should re-read the paragraph just before and after the block of code (and test), if you want to understand more on what Beck was trying to convey.
The last sentence reads "Here is the code we would have to modify to make it work:". That block of code was first entered on page 75 (with test case). Nothing was changed in end effect on page 79. It was just an indication of what we could change, if we wanted to keep this test.
"There is no obvious, clean way to check the currency of the argument if and only if it is Money. The experiment fails, we delete the test, and away we go".
He also stated that this test is ugly and concluded on the following page "Tried a brief experiment, then discarded it when it didn't work out".
I wrote this just in case you were thinking all of the examples just work and should be kept.
Upvotes: 5
Reputation: 17677
You're checking that the sum
variable is a Money
, but returning a Sum
in the plus
method.
So, unless Sum
is a subclass of Money
, that assertion will always fail.
To make it pass, you might want to do something like:
public Expression plus(Expression addend) {
return new Money(...<whatever>...);
}
Of course, Money
would then have to be an Expression
too.
Or you might want to evaluate the sum
to get the money out of it. Or maybe even do sum instanceof Sum
instead. It depends on what behavior you're actually trying to achieve.
By the way, beware the instanceof
operator.
Upvotes: 3