Where to put common setUp-code for differen testclasses?

旧城冷巷雨未停 提交于 2019-12-23 17:43:39

问题


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?


回答1:


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.




回答2:


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.




回答3:


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?




回答4:


I think here are two points to follow:

  • A trade-off between duplicate code and readability.
  • Each unit test case should independent.


来源:https://stackoverflow.com/questions/5354606/where-to-put-common-setup-code-for-differen-testclasses

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!