重构测试代码的最佳实践
我目前在 QA 部门工作,在我的公司,QA 部门的每个人都编写自动化测试。最近我一直在阅读 Martin Fowler 的重构:改进现有代码的设计 。我逐渐意识到我们的许多测试类和测试实用程序非常混乱、冗余,并且迫切需要重构。
特别是自从我一直在阅读该主题以来,我渴望深入研究并清理内容,但有一个问题。福勒在他的书中强调,对重构下的代码进行单元测试对于防止引入错误至关重要。由于我尝试重构的代码是测试代码,因此对它进行单元测试似乎有点愚蠢。你们中有人对如何重构甚至设计测试代码有建议吗?另外,如果有帮助的话,我们使用的测试框架是构建在 JUnit 之上的,因此我所指的测试类是 TestCase 的后代。
谢谢!
I currently have a job in QA and at my company everyone in QA writes automated tests. Recently I have been reading Refactoring: Improving the Design of Existing Code by Martin Fowler. I have come to realize that a lot of our test classes and test utilities are very messy, redundant, and in dire need of refactoring.
Especially since I've been reading up on the topic, I am eager to dive in and clean things up, but there is one problem. In his book, Fowler emphasizes that unit testing the code under refactor is essential to prevent bugs from being introduced. Since the code I am trying to refactor is test code, it seems kind of silly to unit test it. Do any of you guys have suggestions on how to refactor or even design test code? Also, if it helps, the test framework we use is built on top of JUnit and therefore the test classes I'm referring to are descendants of TestCase.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,这并不完全正确。重构的技巧是能够验证您是否保留了功能。
您需要确保所有更改前后都经过验证。这并没有什么特别的。但是,您不需要为该代码编写自动化测试,但这可能会有所帮助。
测试代码复杂重构的技巧是能够针对被测系统运行测试并获得相同的结果。
所以实际上可验证性就是确保输出是相同的。这应该是自动化的。您可以通过多种方式执行此操作,但最简单的方法是输出您正在运行的测试以及正在测试的数据以及您期望的输出和收到的输出。
也许您可以使用一些机器可读的格式(例如 XML)来使其更易于解析。
Nope that's not entirely correct. The trick to re factoring is to be able to verify that you've kept the functionality.
You need to make sure that that all changes are verified before and after. There's not really away around this. However you don't need to write automated tests for that code but it may help.
The trick with complex refactoring of test code is to be able to run the tests against the system under test and get the same results.
So in fact the verifiability is making sure that the output is the same. This should be automated. You can do this in many ways but the simplest would be to output the test you're running with the data you're testing with together with output you expect and the output you receive.
Possibly you can use some machine readable format like XML to make is easier to parse.
我同意上一篇文章的观点,即您应该在修改套件实现之前和之后运行测试套件,以验证其功能是否相同。
您还可以使用更简单的单元测试框架对实现单元测试的代码进行单元测试。如果您的代码继承自 JUnit,则使用 JUnit 来测试它。至少您必须假设 JUnit 可以工作。
I agree with the previous post that you should run your test suite before and after you modify the suite implementation to verify that it functions the same.
You can also unit test code that implements unit tests with an even simpler unit test framework. If your code inherits from JUnit then use JUnit to test it. At a minimum you have to assume that JUnit works.