LINQ to SQL unit testing

Here is a suggestion on how you easily can create integration tests when working with LINQ to SQL and the MSTest unit test framework. I use transactions to roll-back the changes made during the test run. The preparation of the data context and the clean-up is done once for all tests. This is not a clean unit test approach but it minimizes the time spent on preparing the data.

namespace SomeNamespace.Test.IntegrationTests
{
    [TestClass]
    public class SomeTestClass
    {
        private static DataContext Dc;

        [ClassInitialize]
        public static void Initialize(TestContext context)
        {
            // Setup database.
            Dc = new DataContext();
            Dc.Connection.Open();
            Dc.Transaction = Dc.Connection.BeginTransaction();
            // Clear tables.
            Dc.SomeTable.DeleteAllOnSubmit(Dc.SomeTable);
            Dc.SubmitChanges();
        }

        [ClassCleanup]
        public static void Cleanup()
        {
            // Restore database.
            if (Dc == null || Dc.Transaction == null || Dc.Connection == null)
            {
                Debug.WriteLine("Database clean-up failed.");
                return;
            }
            Dc.Transaction.Rollback();
            Dc.Dispose();
        }

        [TestMethod]
        public void SomeMethodUnderTest_NoInput_NoRows()
        {
            Assert.AreEqual(0, Dc.SomeTable.Count());
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *