Petr Kozelka

When is it best to do cleanup in tests ?

04 July 2009 -

With "true" unit tests, having no requirements on shared external resources, this is not an issue.

But in reality, we often need (integration) tests that do need such resources - database, jms, other servers or just files located somewhere.

In my opinion, the cleanup in all unit tests should happen before the test itself. It has a simple reason - whatever wrong happens, next time the test can be executed without need for any annoying manual intervention.

What are the wrong things that may happen ? Here are some:

  • test fails
  • the process is killed - potentially even related to the test execution
  • the host computer is turned off

The first one can be handled by the testing framework. JUnit and similar ones provide support for setUp / teardown method that should do the right things before and after each test or testsuite.

While this concept is very good, especially for isolating the initialization and cleanup code from the test logic, it - by itself - doesn't work at all for the latter scenarios.

So, it is always much safer to assume that we won't get the chance to cleanup afterwards.

My preferred techniques to minimize need for manual intervention are:

  • in the setUp part, prepare all resources to the state required by the test
  • if it is too complex, at least check if they are in the required state; fail with indicative messages otherwise
  • do no init/cleanup stuff within the test method itself
  • do no cleanup in the teardown part - just to avoid temtation to rely on its "proper" function.

One little bonus of not doing cleanup at the end is, that we can easily check the final state of affected resources just by running the single test, with no modification or debugger setup needed.

Fork me on GitHub
Fork me on GitHub