Where to put common setUp-code for differen testclasses?
I have several different test classes that require th开发者_开发问答at 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?
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.
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:
- A trade-off between duplicate code and readability.
- Each unit test case should independent.
精彩评论