I recommend you repeat this daily, “My test code is just as
important as my production code”. I think this is a very good point to remember
when you’re writing tests. All of those principles you apply when writing
production code should be followed with test code. DRY, SOLID, YAGNI, etc. are
all important even with the testing code.
Obviously duplicating code can make your tests difficult to
maintain. What if some business logic changes? If you were repeating yourself
you now have the fun task of going through a dozen tests changing each one, but
if you had not repeated the same code you might have been able to update one
location in the test code. A lot of people are concerned when the line count of
a single file gets large and they will refactor it into multiple manageable
files. This same policy should apply to test classes. If you’ve ever gone into
a test class with way too many classes, you probably know how difficult it can
be to maintain.
Tests exist to make development easier, and if they become
difficult to maintain then something needs to change. I certainly don’t
advocate spending large amounts of time refactoring the tests, but since they
are supposed to increase the longevity of the application they must also be
maintained.