Search code examples
c#integration-testingmstestdummy-data

Integration testing garbage data


I have set up integration testing using MSTest. My integration tests create fake data and insert them into the database (real dependencies). For every business object, I have a method like this, which creates a "Fake" and inserts it into the db:

public static EventAction Mock()
{
    EventAction action = Fixture.Build<EventAction>().Create();
    action.Add(false);
    AddCleanupAction(action.Delete);
    AppendLog("EventAction was created.");
    return action;
}

I clean up all the fakes in [AssemblyCleanup]:

public static void CleanupAllMockData()
{
    foreach (Action action in CleanUpActions)
    {
        try
        {
            action();
        }
        catch
        {
            AppendLog($"Failed to clean up {action.GetType()}. It is possible that it was already cleaned up by parent objects.");
        }
    }
}

Now, I have a big problem. In my continuous integration environment (TeamCity), we have a separate database for testing, and it cleans itself after every test run, but on my local environment, the integration tests point to my local database. Now, If I cancel the test run for any reason, that leaves a bunch of garbage data in my local database, because CleanupAllMockData() never gets called.

What is the best way to handle this? I couldn't find a way to intercept the test cancellation in MSTest.


Solution

  • I see two options for solving your problem:

    1. Cleanup mock data before each start. Only before start.
    2. Each test is wrapped as a db-transaction, which is never commited. I explain this option here