问题描述
什么是好的单元测试? 说测试应该只测试一件事.这样做有什么好处?
What Makes a Good Unit Test? says that a test should test only one thing. What is the benefit from that?
编写更大的测试来测试更大的代码块不是更好吗?无论如何,调查测试失败是很困难的,我认为较小的测试对它没有帮助.
Wouldn't it be better to write a bit bigger tests that test bigger block of code? Investigating a test failure is anyway hard and I don't see help to it from smaller tests.
单词单位不是那么重要.假设我认为该单位更大一些.这不是这里的问题.真正的问题是为什么要对所有方法进行一个或多个测试,因为覆盖多种方法的测试越少越简单.
The word unit is not that important. Let's say I consider the unit a bit bigger. That is not the issue here. The real question is why make a test or more for all methods as few tests that cover many methods is simpler.
一个例子:一个列表类.为什么要对添加和删除进行单独测试?先添加后删除的 one 测试听起来更简单.
An example: A list class. Why should I make separate tests for addition and removal? A one test that first adds then removes sounds simpler.
推荐答案
我要冒昧地说一句,只测试一件事"的建议实际上并不像有时提出的那样有用本来就是.
I'm going to go out on a limb here, and say that the "only test one thing" advice isn't as actually helpful as it's sometimes made out to be.
有时测试需要进行一定数量的设置.有时他们甚至可能需要一定的时间来设置(在现实世界中).通常,您可以一次测试两个操作.
Sometimes tests take a certain amount of setting up. Sometimes they may even take a certain amount of time to set up (in the real world). Often you can test two actions in one go.
Pro:所有设置只发生一次.您在第一个动作之后的测试将证明世界是您在第二个动作之前所期望的样子.更少的代码,更快的测试运行.
Pro: only have all that setup occur once. Your tests after the first action will prove that the world is how you expect it to be before the second action. Less code, faster test run.
缺点:如果任一操作失败,您将得到相同的结果:相同的测试将失败.与在两个测试中的每一个中只执行一个操作相比,您获得的关于问题所在的信息会更少.
Con: if either action fails, you'll get the same result: the same test will fail. You'll have less information about where the problem is than if you only had a single action in each of two tests.
实际上,我发现这里的骗局"并不是什么大问题.堆栈跟踪通常会很快缩小范围,无论如何我都会确保我修复了代码.
In reality, I find that the "con" here isn't much of a problem. The stack trace often narrows things down very quickly, and I'm going to make sure I fix the code anyway.
这里的一个稍微不同的缺点"是它打破了编写新测试,使其通过,重构"循环.我认为这是一个理想周期,但并不总是反映现实.有时,在当前测试中添加一个额外的动作并检查(或者可能只是对现有动作的另一个检查)比创建一个新的更实用.
A slightly different "con" here is that it breaks the "write a new test, make it pass, refactor" cycle. I view that as an ideal cycle, but one which doesn't always mirror reality. Sometimes it's simply more pragmatic to add an extra action and check (or possibly just another check to an existing action) in a current test than to create a new one.
这篇关于为什么单元测试应该只测试一件事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!