Search code examples
sql-serverautomated-testssnapshotdata-consistency

Handle database snapshots in multi user Environment in SQL Server in C#


I have written some tests in C# which make use of database, update and modify values in it. To make sure that the database is reverted to its prior state after each test, I do the following:

I make a snapshot of all databases used in the beginning of test suite. After each test, I revert database to its snapshot to make sure that are no changes made to database for new test case that is about to run. At the end of test suite I delete the snapshots created.

Here are initialize and cleanup methods of test class

    [ClassInitialize()]
    public static void ClassInit(TestContext context)
    {
        CreateDatabaseSnapshots();
    }

    [ClassCleanup()]
    public static void ClassCleanup()
    {
        DeleteDatabaseSnapshots();
    }

This is method executed after each test in the test suite.

    [TestCleanup()]
    public void TestCleanup()
    {
      tRevertDatabase();
    }

My problem : in a multi-user environment how shall I handle the task of creating database snapshots? One may create incorrect snapshots while my test suite is still running and his/her tests might fail, or even database may be reverted back to incorrect state at end of test suite. What necessary checks has to be done before calling CreateDatabaseSnapshots(); and DeleteDatabaseSnapshots();?

I want just to ensure that the database is not affected in process of testing. I have tried using alternate database, transaction scope and other alternatives too but they cannot be used in my scenario so using snapshots is the only feasible option.


Solution

  • Instead of modifying on the environment of your database, why not do these instead:

    1.) Take database snapshot of your database.
    2.) Attach database snapshot to the local machine of the test-user. (Test initialize)
    3.) Modify the database on the test environment of the user during automated testing.
    

    Note: You can stop resetting the database back to the original state during clean up because every time your test initializes your are creating a fresh local copy of the target database. (Or just dispose of the local database copy)

    During testing, there are times that you want to have your OWN test environment unless your test scenarios should compose of data modifications coming from different testers.