Click here to Skip to main content
15,896,606 members
Articles / DevOps / Unit Testing

Two Strategies for Testing Entity Framework - Effort and SQL CE

Rate me:
Please Sign up or sign in to vote.
4.97/5 (14 votes)
19 Sep 2012CPOL6 min read 118K   2.5K   27  
Two approaches for unit testing Entity Framework
In this article, you will learn about two approaches for unit testing Entity Framework: Mocking in memory by using "Effort", and against a real database using SQLCE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TestingEf.Data.Entities;
using System.Configuration;
using System.IO;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlServerCe;

namespace TestingEf.Data.Tests.TestDatabaseStrategies
{
    public class SqlCeDatabaseStrategy : ITestDatabaseStrategy
    {
        public SqlCeDatabaseStrategy() :
            this("RealMyAppDb")
        {
        }

        public SqlCeDatabaseStrategy(string databaseName)
        {
            DatabaseName = databaseName;
        }

        public string DatabaseName { get; private set; }

        public bool DatabaseInitialized { get; private set; }

        public IMyAppContext CreateContext()
        {
            // create the database from scratch if it has not been initialised
            if (!DatabaseInitialized)
            {
                // get the path to the .SDF file
                var fullPath = GetRealDatabaseFilePath(DatabaseName);

                // delete it if it already exists
                if (File.Exists(fullPath))
                    File.Delete(fullPath);

                // get the SQL CE connection string
                string connectionString = GetRealDatabaseConnectionString(DatabaseName);

                // NEED TO SET THIS TO MAKE DATABASE CREATION WORK WITH SQL CE!!!
                Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
                
                using (var context = new MyAppContext(connectionString))
                {
                    context.Database.Create();
                }

                // Set the initialised flag so that we don't re-create the database again for this instance of the class
                DatabaseInitialized = true;
            }

            // create the DbContext with the SQL CE connection string
            return new MyAppContext(GetRealDatabaseConnectionString(DatabaseName));
        }

        public void Dispose(IMyAppContext context)
        {
            try
            {
                Dispose();
            }
            finally
            {
                if (context != null)
                {
                    context.Dispose();
                }
            }
        }

        public void Dispose()
        {
            // delete the database
            var fullPath = GetRealDatabaseFilePath(DatabaseName);

            if (File.Exists(fullPath))
            {
                File.Delete(fullPath);
            }

            DatabaseInitialized = false;
        }

        private static string GetRealDatabaseFilePath(string databaseName)
        {
            var directory = ConfigurationManager.AppSettings["TempDatabaseFolder"];
            var fileName = String.Format("{0}.sdf", databaseName);

            return System.IO.Path.Combine(directory, fileName);
        }

        private static string GetRealDatabaseConnectionString(string databaseName)
        {
            return string.Format("Data Source = {0}", GetRealDatabaseFilePath(databaseName));
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions