0

Unit testing data access code

Posted in .Net, C#, Development, Unit Testing at February 19th, 2008 by Ben /

A classic problem to unit testing code that modifies the underlying data in the database tables is that you need to find a way to revert back to the original database state so that the tests can be run over and over again.

Using the transaction capabilities provided with the .Net 2.0 framework and a unit testing framework you can achieve this easily.

The process:

  • Create a new transaction before each test.
  • Dispose (Rollback) the transaction after each test.


    using System.Data;

    [TestClass]
    public class DataProviderTest {

        private readonly DataProvider _dp = new DataProvider();
        private TransactionScope _transactionScope;

        [TestInitialize]
        public void TestInitialize() {
            _transactionScope = new TransactionScope();
        }

        [TestCleanup]
        public void TestCleanup() {
            _transactionScope.Dispose();
        }

        [TestMethod]
        public void InsertTest()
        {
            // modify the database
            ...
        }
    }
Published in .Net, C#, Development, Unit Testing

No Responses to “Unit testing data access code”

Leave a Reply