Peter Kellner
Peter Kellner

Reputation: 15488

How To Unit Test Entity Framework With Seeded Data

I'm thinking that it makes sense to test my VS2015 EF Code First project with the data that gets created with seeding. It's not clear to me what should be in the test project in terms of setup and teardown and the actual tests.

Is there an example someone can point me at that shows this? Also, am I off base thinking this is a good way to test (seeded data). I have not been able to find examples of that. The examples I see seem a lot more complex with mocking data instead.

Upvotes: 1

Views: 680

Answers (1)

Dave
Dave

Reputation: 1593

You haven't specified whether you are using MSTest or not, but I just had this problem today and this is what I did using MSTest. This base test class handles the seeding on the first test that runs. The Initialize(false) makes it that it wont try to initialize on secondary test runs so only the first test pays the setup price. Since each test is in a transaction they will rollback the changes made in each test.

[TestClass]
public abstract class EntityFrameworkTest
{
    private static bool _hasSeeded;

    protected TransactionScope Scope;

    [TestInitialize]
    public void Initialize()
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<YourContext, YourModelNameSpace.Migrations.Configuration>());
        using (var context = new YourContext())
        {
            context.Database.Initialize(false);
            if (!_hasSeeded)
            {
                context.AnEntity.AddOrUpdate(c => c.EntityName, new AnEntity {EntityName = "Testing Entity 1"});
                context.SaveChanges();
                _hasSeeded = true;
            }
        }

        Scope = new TransactionScope();
    }

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

    [AssemblyCleanup]
    public static void KillDb()
    {
        using (var context = new YourContext())
            context.Database.Delete();
    }
}

It is also worth noting that I setup my test project app.config with a connection string like this that my context is set to look for (ConnStringName). The desire being here that each devs machine will just create a Testing db in their local db and wont have to fiddle with changing the connection string to something if their actual SQL instance setup is different. Also, depending on if you are VS 2015 or not, your local DB data source may vary.

<add name="ConnStringName" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=DbNameTestingInstance; Integrated Security=True; MultipleActiveResultSets=True;Application Name=Testing Framework;" providerName="System.Data.SqlClient" />

Upvotes: 1

Related Questions