应该是“安排-断言-行动-断言"吗? [英] Should it be "Arrange-Assert-Act-Assert"?

查看:29
本文介绍了应该是“安排-断言-行动-断言"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 Arrange-Act-Assert 的经典测试模式,我经常发现自己添加了一个在法案之前的反断言.这样我就知道传递的断言实际上是作为动作的结果传递的.

Regarding the classic test pattern of Arrange-Act-Assert, I frequently find myself adding a counter-assertion that precedes Act. This way I know that the passing assertion is really passing as the result of the action.

我认为它类似于 red-green-refactor 中的红色,只有当我在测试过程中看到红色条时,我才知道绿色条意味着我编写的代码使有区别.如果我写了一个通过的测试,那么任何代码都会满足它;同样,关于安排-断言-行为-断言,如果我的第一个断言失败,我知道任何法案都会通过最后的断言 - 所以它实际上并没有验证关于该法案的任何事情.

I think of it as analogous to the red in red-green-refactor, where only if I've seen the red bar in the course of my testing do I know that the green bar means I've written code that makes a difference. If I write a passing test, then any code will satisfy it; similarly, with respect to Arrange-Assert-Act-Assert, if my first assertion fails, I know that any Act would have passed the final Assert - so that it wasn't actually verifying anything about the Act.

您的测试是否遵循这种模式?为什么或为什么不?

Do your tests follow this pattern? Why or why not?

更新 澄清:初始断言本质上与最终断言相反.这并不是说安排"有效;断言法案尚未奏效.

Update Clarification: the initial assertion is essentially the opposite of the final assertion. It's not an assertion that Arrange worked; it's an assertion that Act hasn't yet worked.

推荐答案

这是一个例子.

public void testEncompass() throws Exception {
    Range range = new Range(0, 5);
    assertFalse(range.includes(7));
    range.encompass(7);
    assertTrue(range.includes(7));
}

可能是我写了 Range.includes() 来简单地返回 true.我没有,但我可以想象我可能有.或者我可能会以任何其他方式写错.我希望并期望使用 TDD 我实际上是正确的 - includes() 可以正常工作 - 但也许我没有.所以第一个断言是一个健全性检查,以确保第二个断言真的有意义.

It could be that I wrote Range.includes() to simply return true. I didn't, but I can imagine that I might have. Or I could have written it wrong in any number of other ways. I would hope and expect that with TDD I actually got it right - that includes() just works - but maybe I didn't. So the first assertion is a sanity check, to ensure that the second assertion is really meaningful.

自行阅读,assertTrue(range.includes(7)); 是说:断言修改的范围包括 7".在第一个断言的上下文中阅读,它说:断言 调用 encompass() 导致它包含 7.而且由于 encompass 是我们正在测试的单元,我认为这是一些(小) 值.

Read by itself, assertTrue(range.includes(7)); is saying: "assert that the modified range includes 7". Read in the context of the first assertion, it's saying: "assert that invoking encompass() causes it to include 7. And since encompass is the unit we're testing, I think that's of some (small) value.

我接受我自己的答案;许多其他人将我的问题误解为关于测试设置.我认为这略有不同.

I'm accepting my own answer; a lot of the others misconstrued my question to be about testing the setup. I think this is slightly different.

这篇关于应该是“安排-断言-行动-断言"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆