来自 Kent Beck 的 TDD 的货币示例
因此,我已经完成了 Kent Beck 的《测试驱动开发示例》一书中的 Money 示例,并且能够使代码正常工作,直到他编写的最后一个测试:
@Test
public void testPlusSameCurrencyReturnsMoney(){
Expression sum = Money.dollar(1).plus(Money.dollar(1));
assertTrue(sum instanceof Money);
}
这是这个函数 当我运行这个时,
public Expression plus(Expression addend) {
return new Sum(this, addend);
}
它给出了 java.lang.AssertionError ,所以我的问题是为什么它会给出这个错误以及如何修复它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Lunivore 已经回答了如何解决问题的问题,但我认为如果您想更多地了解 Beck 试图传达的内容,您应该重新阅读代码块(和测试)之前和之后的段落。
最后一句是“这是我们必须修改才能使其工作的代码:”。该代码块首先在第 75 页上输入(带有测试用例)。第 79 页的最终效果没有任何更改。这只是表明如果我们想保留此测试,我们可以更改哪些内容。
“当且仅当它是金钱时,没有明显、干净的方法来检查参数的货币。实验失败了,我们删除了测试,然后就走了”。
他还表示这个测试很丑陋,并在下一页总结道“尝试了一个简短的实验,但没有成功就放弃了”。
我写这篇文章是为了防止您认为所有示例都有效并且应该保留。
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.
您正在检查
sum
变量是否为Money
,但在plus
方法中返回Sum
。因此,除非
Sum
是Money
的子类,否则该断言将始终失败。为了使其通过,您可能需要执行以下操作:
当然,
Money
也必须是一个Expression
。或者您可能想评估
总和
以从中获利。或者甚至可以使用sum instanceof Sum
来代替。这取决于您实际想要实现的行为。顺便说一下,要小心
instanceof
运算符。You're checking that the
sum
variable is aMoney
, but returning aSum
in theplus
method.So, unless
Sum
is a subclass ofMoney
, that assertion will always fail.To make it pass, you might want to do something like:
Of course,
Money
would then have to be anExpression
too.Or you might want to evaluate the
sum
to get the money out of it. Or maybe even dosum instanceof Sum
instead. It depends on what behavior you're actually trying to achieve.By the way, beware the
instanceof
operator.