Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

entity framework - Recreate and Reseed LocalDb Before Each Unit Test

I'm attempting to write unit/integration tests for my ASP.NET Web API project and struggling to run each test in isolation. Allow me to explain.

I have a *.testsettings file with deployment settings configured. Before each test run, an empty *.mdf file is deployed to the test location. Since I'm using Entity Framework Code First, I can use a database initializer to push my schema to the database and seed a particular table with 2 rows. This works great.

The problem I'm facing is that the various tests for all of my ApiControllers' actions can step on each other's toes if they execute in the wrong order. For example, if I run the GET test before the POST test then GET returns 2 objects with if they are run in the reverse order then GET returns 3 objects.

What I think I need to do is drop, recreate and reseed my database before every test. Is this a good idea or is there are better way? If this is the best I can do, I would I go about resetting my database before each test.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...