原文链接:https://dzone.com/articles/tests-are-for-the-future
为未来测试。测试提供文档,帮助你避免回归,让你在重构时充满自信。
想象一下:你刚写下一些有关新功能的代码,正在用单元测试把它们封装起来。而当你写下这些测试代码的时候,你开始反思这么做的必要性。“我为什么要写这些测试?”你问自己。“我已经手动验证过这些代码,甚至另一个开发也验证过。有什么必要吗?”
问题的答案,决定于一个重要的认知:你是为未来而测试。
当然,测试也是为了当下,可以帮助你覆盖一些开发新功能时、可能忽略掉的极端情况。
但测试的目的,主要还是为了人——那些在接下来的数月数年里、会接手你的代码的人。
我们来分析一下。
文档
测试能提供文档,以描述指定功能应有的表现。
测试本质上是产品需求的代码形式。也许之后接手的开发人员会对代码的目的、或覆盖哪些场景有一些疑问。
比起深究早期的JIRA tickets,或者到处托管的过时文档,开发者可以直接在IDE中跳转到测试组件。通过看测试用例,他们能更好的理解该功能的工作原理。
避免回归
测试可以帮助你在开发新功能时,避免对整个代码库进行回归。
虽然这些新特性看上去与一些现存代码无关,但这种情况仍有可能发生——他们以某种方法联系起来,而你看漏了。
可靠的测试组件能跟踪到你消极应对的、不小心影响到的现存代码。
没有恰如其分的测试,你绝不可能对你写下的代码(在没有大范围且乏味的手动测试下)能兼容旧代码有充足自信。
Refactoring
The most compelling reason for writing tests and why they are for the future is that they allow you to refactor with confidence.
I’m sure you’ve worked somewhere that has a large legacy application the team is supporting. There is something absolutely crucial buried in that legacy application. Maybe it’s your payment processing business logic. Maybe it’s your authentication code.
Whatever it is, it’s essential to the core functionality of your application, and everyone is scared to touch it. It’s old and seems to be working properly, but it’s turned into a huge mess of spaghetti code that no one really understands anymore.
And why is everyone scared to work on it? Because it doesn’t have any tests! And that means that any line of code you change opens up the possibility of breaking something without your knowledge. It means that every small change you make to this piece of functionality needs to be heavily manually tested. It means that you get extremely nervous and cross your fingers as you click the “Submit” button to merge your code.
Now, in an alternate reality, imagine that same piece of core functionality, but with a nice test suite that adequately covers the code. When it comes time to refactor the code, you can do so with confidence. Why? Because you’ll know if you’ve broken something. If the tests are all passing now, you make some changes, and now you have a few failures, it’s clear that something isn’t quite right yet.
But that’s not troubling because you’ve caught the errors before you’ve released these new changes to production and you’re able to find the root cause and make sure your refactor is working properly this time.
Conclusion
Tests are for the future. They provide documentation, help you avoid regressions, and allow you to refactor with confidence.