1

I find myself repeating the same code when writing unit tests, for example... When writing functions that work with files, In the setup for the test i often write some code to create a file (in a directory specified with an environment variable) populate it then after i have run the test I destroy the file and folder.

To me this seems the correct way of doing things as the test is completely independent of anything other than an environment variable which can easily be set on multiple os's.

However I am clearly violating DRY principle by writing this file creating code every time, so I thought I could make a helper package that simplifies this, however i feel that would mean the test would become "dependant" on the helper package.

So the questions are.

  1. In this situation should the DRY principle be violated so as to avoid unnecessary dependence's?

  2. It's ok to create a helper package as long as it can be imported from an external location like git hub?

    1. Is there another approach (perhaps using dependency injection)?
1
  • I don’t see why you would treat your test code with lower quality than the other code. It is part of the project and will be read, used and modify as much as any other code. It is equally important. Jul 17, 2019 at 13:16

1 Answer 1

2

While in test code a higher amount of repetition is accepted than in production code, there are limits. When you are constantly repeating the same setup and/or cleanup code, then a refactoring to make the code more DRY is in order.

The possibilities to DRY up your test code depend to some extent on the features offered by your testing framework.

  • Many test frameworks allow testcases to be grouped with common setUp/tearDown functions that are called automatically before/after each testcase. These functions are specifically designed to perform setup and cleanup tasks that are common to all testcases within the group.
  • Some test frameworks allow grouping of testcases and test sets in a deeper hierarchy. Most of those allow the specification of setUp/tearDown functions for test sets (called once when the test set starts/ends), but some even allow higher level test sets to specify setUp/tearDown functions that are executed per test case within the nested test sets.
  • Moving the code to a separate "test_helpers" module is always an option. Having your test code be dependent on such a module is not a problem at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.