Monday, March 05, 2012

Unit Testing an Entity Framework Data Access Layer

One approach to write unit tests for a data access layer implemented using Entity Framework that targets SQL Server is to use a local test database SQL Server Compact Edition. The test database will have the same schema as the real application database, and it will contain the minimun necessary data for your test cases. 

The only thing to keep in mind is that you will need to restore the previous state of the test database after each unit test run. There are multiple approaches such as to recreate the database before each test or simply restore a backup file. One approach that I like is to run the test under a TransactionScope.  In this approach, you create a TransactionScope object before the test runs and call TransactionScope.Dispose after the test is completed. Since TransactionScope.Complete is not called, the Dispose method will rollback the changes. That is, you SQL Compact database will be back to the state before running the test.

If you are using xUnit, then your unit test class will need to implement the IDisposable interface, create the TransactionScope in the constructor and dispose it in the Dispose method as shown below:

public class MyDataAccessUnitTests : IDisposable
{
  private TransactionScope _transactionScope;

  public MyDataAccessUnitTests()
  {
    _transactionScope = new TransactionScope();
  }

  [Fact]
  void Test1()
  {
    // TODO: implement it.
  }

  [Fact]
  void Test2()
  {
    // TODO: implement it.
  }

  public void Dispose()
  {
    _transactionScope.Dispose();
  }
}


If you are using NUnit or MSTest, then you can create and dispose the TransactionScope object in the following methods:

xUnit NUnit MSTest
new TransactionScope() Constructor [SetUp] [TestInitialize]
TransactionScope.Dispose IDisposable.Dispose [TearDown] [TestCleanup]

I hope this helps!