2011-12-07 26 views
0

我使用MVC3 EF 4.2代码首先使用存储库模式的现有数据库。MVC3 EF 4.2上的集成测试导致错误:自创建数据库以来支持上下文的模型已更改

当使用EF代码第一次没有初始化器在Global.asax的Application_Start(设置现有的数据库)和DbSet通过移除复数化公约映射到我的数据库表:

public DbSet<Role> Roles { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 
    } 

我的表称为角色。

我的第一个测试将一个模拟库传递给控制器​​。

[TestMethod] 
    public void Index_Contains_All_Roles() 
    { 
     // Arrange - create the mock repository 
     Mock<IRoleRepository> mock = new Mock<IRoleRepository>(); 
     mock.Setup(m => m.Roles).Returns(new Role[] { 
      new Role { Id = 1, Name = "Admin" }, 
      new Role { Id = 2, Name = "Manager" }, 
      new Role { Id = 3, Name = "Examiner" }, 
      new Role { Id = 4, Name = "Examinee" } 
     }.AsQueryable()); 

     // Arrange - create a controller 
     RoleController target = new RoleController(mock.Object); 

     // Action 
     Role[] result = ((IEnumerable<Role>)target.Index().Model).ToArray(); 

     // Assert 
     Assert.IsTrue(result.Length == 4); 
     Assert.AreEqual("Admin", result[0].Name); 
     Assert.AreEqual("Manager", result[1].Name); 
     Assert.AreEqual("Examiner", result[2].Name); 
     Assert.AreEqual("Examinee", result[3].Name);    
    } 

第一次测试通过。

第二个测试是一个集成测试,用于检查数据库是否包含正确的角色。

[TestMethod] 
    public void Database_Contains_All_Roles() 
    { 
     // Arrange - create repository 
     IRoleRepository roleRepository = new RoleRepository(); 

     // Arrange - create a controller 
     RoleController target = new RoleController(roleRepository); 

     // Action 
     Role[] result = ((IEnumerable<Role>)target.Index().Model).ToArray(); 

     // Assert 
     Assert.IsTrue(result.Length == 4); 
     Assert.AreEqual("Admin", result[0].Name); 
     Assert.AreEqual("Manager", result[1].Name); 
     Assert.AreEqual("Examiner", result[2].Name); 
     Assert.AreEqual("Examinee", result[3].Name); 
    } 

当我运行第二个测试,我得到一个错误:

The model backing the 'MyDbContext' context has changed since the database was created 

然而,在Web浏览器中查看实际控制从数据库加载正确的数据。

我缺少什么?

回答

0

这是一个老问题,需要一个数据库初始化设置为null在Global.asax中

Database.SetInitializer<YourDbContext>(null); 
+0

谢谢回答。我已阅读关于该问题的帖子。但是,在浏览器中查看实际控制器并且正确地从数据库加载数据时,我不会收到任何错误。运行单元/(集成)测试时,我只会遇到错误。 – stormwild

相关问题