Recreate and Reseed LocalDb Before Each Unit Test

这一生的挚爱 提交于 2019-11-28 20:45:50
Raymond Saltrelli

Here's what I ended up doing for anyone that is interested.

I extended DropCreateDatabaseAlways<TContext> and overrode the Seed method to populate my database with known test data that my unit tests can rely on.

public class MyDatabaseInitializer : System.Data.Entity.DropCreateDatabaseAlways<MyDbContext>
{
    protected override void Seed(MyDbContext context)
    {
        // Add entities to database.

        context.SaveChanges();
    }
}

I then implemented an [AssemblyInitialize] method which sets the database initializer.

[TestClass]
public class Global
{
    [AssemblyInitialize]
    public static void AssemblyInitialize(TestContext context)
    {
        System.Data.Entity.Database.SetInitializer(new MyDatabaseInitializer());
    }
}

This sets the initializer for the database but does not actually run it. The intitializer is run in a [TestInitialize] method I wrote which forces the database to be dropped, recreated and reseeded before each test.

[TestClass]
public class MyTestClass
{
    [TestInitialize]
    public void TestInitialize()
    {
        MyDbContext context = new MyDbContext();
        context.Database.Initialize(true);
    }

    [TestMethod]
    public void MyUnitTest()
    {
        Assert.IsTrue(true);
    }
}

I would suggest re-creating your database before you begin your tests and then wrap each in a transaction that always rolls back. This is quite beneficial if your recreate stage takes a lot of time to complete (e.g. because of the actions that need to be performed, etc.).

In our current setup we're recreating the database schema before each class is loaded (with ClassInitialize attribute, but this could definitely be moved to AssemblyInitialize), and just seeding/cleaning up the database with the appropriate records before/after each test run (with TestInitialize/TestCleanup attribute).

More info: http://msdn.microsoft.com/en-us/library/ms379625(v=vs.80).aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!