Cleanup and Arrange Practices During Integration Testing

cintegration-testsprogramming practicestesting

I'm coding tests in C# and I settled with this structure:

try
{
    // ==========
    // ARRANGE
    // ==========

    // Insert into the database all test data I'll need during the test

    // ==========
    // ACT
    // ==========

    // Do what needs to be tested

    // ==========
    // ASSERT
    // ==========

    // Check for correct behavior
}
finally
{
    // ==========
    // CLEANUP
    // ==========

    // Inverse of ARRANGE, delete the test data inserted during this test
}

The concept was "every test cleans up the mess it makes". However, some tests are leaving the database dirty and the failing the tests that come after.

What's the right way to do this? (minimize errors, minimize run time)

  • Deletes everything » Insert defaults » Insert test data » Run test?
  • Insert defaults » Insert test data » Run test » Delete everything?

  • Currently:

    • (per session) Deletes everything » Insert defaults
    • (per test) Insert test data » Run test » Delete test data

Best Answer

Besides the fact that this is an integration test as opposed to a unit test, the operations you describe typically go in Setup and/or Teardown methods. Frameworks like nUnit allow one to decorate class methods with these attributes to indicate whether the method is a setup method or teardown method.

Then your tests should become cleaner and smaller as the setup and cleanup is done outside of the test itself.

Most likely multiple tests can re-use the same data so that is a plus as well as opposed to insert/remove on every test. Going back to nUnit, the FixtureSetup and FixtureTeardown attributes help to setup data for multiple tests at once.

I would use a test framework over a try/catch as many of these testing features are built into the framework itself. xUnit, nUnit, even the Microsoft built in testing framework are all solid choices and will help with the setup and clean up of database records in a consistent fashion.

Related Topic