在哪里放置不同测试类的通用设置代码?
我有几个不同的测试类,它们要求在运行这些测试之前创建某些对象。现在我想知道是否应该将对象初始化代码放入单独的帮助器类或超类中。
这样做肯定会减少我的测试类中重复代码的数量,但也会降低它们的可读性。
是否有如何处理单元测试的常见设置代码的指南或模式?
I have several different test classes that require that certain objects are created before those tests can be run. Now I'm wondering if I should put the object initialization code into a separate helper class or superclass.
Doing so would surely reduce the amount of duplicate code in my test classes but it would also make them less readable.
Is there a guideline or pattern how to deal with common setUp-code for unit tests?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
处理测试代码时的模式和实践与您正在测试的代码没有什么不同。相同的面向对象原则和实践应该存在于您的测试代码中,但有一点需要注意。如果您采取的方法使单元测试难以找到故障点……那么您就做错了。
Patterns and practices when dealing with test code is no different then the code which you are testing. The same OO principles and practices should exist within your test code, with one caveat. If the approach you take makes the unit test difficult to find the failure point...you are doing it wrong.
我不太同意将常见的东西(在您的情况下是对象初始化)放在共享/基类中会对代码的可读性产生影响。
事实上,重构的整个基础是关于如何以提高代码可读性的方式组织代码!
希望有帮助。
I don't quite agree that putting the common stuff ( object initialization in your case) in a shared/base class would have the impact on readability of your code.
In fact whole basis of Refactoring is about how to organize your code in a manner that you improve readability of it!
Hope that helps.
是的,有。
这正是 setUp() 和 Teardown() 函数的原因。您应该使用 setUp() 函数准备测试,并在 Teardown 中的测试之后执行作业。如果对同一对象有多个 Test,则应考虑使用 Test 超类,在其中使用 setUp() 来启动该对象。
检查如何为我的所有测试运行一次setUp()和tearDown()代码?
Yes there is.
Thats exactly the reason for the setUp() and Teardown() functions. you should prepare for your test using the setUp() function, and do the Jobs after the Test in the Teardown. If you have more than one Test on the same object you should consider a Testsuperclass in which you use the setUp() to initiate this object.
Check How can I run setUp() and tearDown() code once for all of my tests?
我认为这里有两点需要遵循:
I think here are two points to follow: