如何知道您的单元测试是否“大小合适”?
我在单元测试中一直注意到的一件事是它们变得有点冗长;鉴于它们也可能不够详细,您如何了解单元测试的大小何时合适?
我知道对此有一个很好的引用,它是:
“完美是实现的,而不是当 没有什么可以添加的,但是当 没有什么可以删除的了。” - 安托万·德·圣埃克苏佩里。
One thing that I've always noticed with my unit tests is that they get to be kind of verbose; seeing as they could also be not verbose enough, how do you get a sense of when your unit tests are the right size?
I know of a good quote for this and it's:
"Perfection is achieved, not when
there is nothing left to add, but when
there is nothing left to remove."
- Antoine de Saint-Exupery.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
他们变得冗长的原因之一是他们正在测试多种东西。我尝试让每个单元测试测试一件事,并且仅测试一件事。因此,我最终进行了大量测试,每个测试都断言一个功能。它运作良好,因为在做出其他断言之前,一次失败不会通过退出单元测试来掩盖另一次失败。
编写这样的细粒度测试意味着,如果您不小心,您将重复大量设置/拆卸代码,而这就是您需要花时间处理的内容,将其抽象出来(以任何合适的方式)。
One reason why them become verbose is that they're testing multiple things. I try to make each unit test test one thing, and one thing only. So I end up with a lot of tests, each asserting one piece of functionality. It works well since a failure won't disguise another failure by bailing out of the unit test before other assertions are made.
Writing fine-grained tests like this means that if you're not careful, you'll duplicate a lot of setup/teardown code, and that's the stuff you need to spend time on, abstracting it out (in whatever way is suitable).
我知道当代码中的一件事发生变化可能导致测试失败时,就会完成单元测试。如果测试的东西太多,现在可能很好,但在将来再次运行测试时对我没有帮助。我希望失败的测试能准确地指出导致失败的原因,而不是完整的可能性列表。
I know a unit test is done when one thing changing in the code could cause the test to fail. If it's testing too many things, that might be good right now, but doesn't help me in the future when I run the test again. I want a failing test to point me right to the thing that caused the failure, not a whole list of possibilities.
我从来没有太担心单元测试是否是真正干净、简短和简洁的代码。有时我有 100 行函数,在单元测试中需要大量复制和粘贴,考虑到大多数单元测试都设置一些虚拟数据,然后根据该数据测试正确的结果,我不认为这是一个太大的问题。
但是,我会说,当我想不出代码中的任何一件事可能是错误的时,我知道我有足够的单元测试。
编辑
回应您的编辑:我不寻求单元测试的完美。
I've never worried too much about the unit tests being really clean, short and concise code. Sometimes I have 100 line functions which are lots of copy and paste in unit tests, and I don't see that as too large a problem considering most unit tests are setting up some dummy data, and then testing for the correct results based on that.
However, I would say I know I have enough unit tests when I can't think of a single thing in the code which could be wrong.
Edit
In response to your edit: I don't look for perfection in unit tests.