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
    public class SomeTestClass
        private static DataContext Dc;

        public static void Initialize(TestContext context)
            // Setup database.
            Dc = new DataContext();
            Dc.Transaction = Dc.Connection.BeginTransaction();
            // Clear tables.

        public static void Cleanup()
            // Restore database.
            if (Dc == null || Dc.Transaction == null || Dc.Connection == null)
                Debug.WriteLine("Database clean-up failed.");

        public void SomeMethodUnderTest_NoInput_NoRows()
            Assert.AreEqual(0, Dc.SomeTable.Count());

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.