samedi 23 juillet 2016

Reusing InMemoryDatabase across unit tests

I have ASP.NET MVC Core application that I am writing Unit tests for. I am using InMemoryDatabase and it is working great. I want to initialize database once for the test run. So, I have a static class:

public static class DbInitialize {
    private static MyDbContext _db;

    public static MyDbContext Initialize() {
        if (_db != null) {
            return _db;
        }
        DbContextOptionsBuilder<MyDbContext> optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        optionsBuilder.UseInMemoryDatabase();
        _db = new MyDbContext(optionsBuilder.Options);
       ....... (populating mock data) .............
       _db.SaveChanges();
       return _db;
    }
}

Works great for a single test class (say, HomeControllerTests) and all its specific tests. However, if I have another test class (CustomerControllerTests) and I call DbInitialize.Initialize() - I see that _db is null, but the database was not destroyed - I get Key error during SaveChanges(). Is there a better way to initialize the database only once, and get a "connection string" (for lack of better word) if it is already up and running?

Aucun commentaire:

Enregistrer un commentaire