Fake DbContext of Entity Framework 4.1 to Test

前端 未结 5 1820
再見小時候
再見小時候 2020-11-22 17:19

I\'m using this tutorial to Fake my DbContext and test: http://refactorthis.wordpress.com/2011/05/31/mock-faking-dbcontext-in-entity-framework-4-1-with-a-generic-repository/

5条回答
  •  情话喂你
    2020-11-22 17:50

    As Ladislav Mrnka mentioned, you should test Linq-to-Entity but not Linq-to-Object. I normally used Sql CE as testing DB and always recreate the database before each test. This may make test a little bit slow but so far I'm OK with the performance for my 100+ unit tests.

    First, change the connection string setting with SqlCe in the App.config of you test project.

    
        
    
    

    Second, set the db initializer with DropCreateDatabaseAlways.

    Database.SetInitializer(new DropCreateDatabaseAlways());
    

    And Then, force EF to initialize before running each test.

    public void Setup() {
        Database.SetInitializer(new DropCreateDatabaseAlways());
    
        context = new MyDbContext();
        context.Database.Initialize(force: true);
    }
    

    If you are using xunit, call Setup method in your constructor. If you are using MSTest, put TestInitializeAttribute on that method. If nunit.......

提交回复
热议问题