简体   繁体   中英

Entity Framework C# Code First Migration Unit Testing


I would like to be able to unit test using my code first/migrations entity framework project.

My current method does the following:

  1. Create the DataContext
  2. Creates the repository
  3. Creares unit of working using DataContext
  4. Creates my service layer

After step 1. I would like to be able say to entity framework, using my migrations/migrations folder recreate the database every time it runs.

I current send in my Datacontext a custom string which represents what connection string to use, my code looks like:

    [TestCase]
    public void TestMethod1()
    {

        var systemContextTest = new SystemContext("SystemContextTest");
        IRepository<PublicQueries> repos = new Repository<PublicQueries>(systemContextTest);
        var uow = new UnitOfWork(systemContextTest);
        var service = new PublicQueryService(repos);
        service.Find(0);
    }

I just want to be able to create the database, using migrations everytime this test is ran!

Thanks

-UPDATE-

I have tried:

Database.SetInitializer<YourContext>(new MigrateDatabaseToLatestVersion<YourContext, YourMigrationConfiguration>());

But this results in

System.Data.Entity.Core.EntityCommandExecutionException : An error occurred while executing the command definition. See the inner exception for details. ----> System.Data.SqlClient.SqlException : Invalid object name

Which means its still not creating it.

I just want to using my migration files/code first migrations to create a new fresh database.

-- UPDATE 2 --

When adding Database.SetInitializer(new DropCreateDatabaseAlways<SystemContext>());

I get the following error:

System.InvalidOperationException : The DropCreateDatabaseAlways initializer did not drop or create the database backing context 'SystemContext' because Migrations are enabled for the context. Use Migrations to manage the database for this context, for example by running the 'Update-Database' command from the Package Manager Console.

My SystemContext Constructor i am using for testing looks like:

      public SystemContext(string connectionstringname) :
        base(connectionstringname)
    {
        Database.SetInitializer<SystemContext>(null);
        Configuration.ProxyCreationEnabled = false;
    }

Updatad answer:

Implement a custom database initializer

private DbMigrationsConfiguration configuration;

public void InitializeDatabase(C context) {
    context.Database.Delete();
    context.Database.Create();

    var migrator = new DbMigrator(configuration);
    migrator.Update();
}

and put this line at the beginning of the test method.

Database.SetInitializer(new MyCustomInitializer<SystemContext>());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM