0

任何单位测试包括呼叫(使用LINQ)从我的DbContext数据引发以下错误进行选择:异常从单元测试访问的DbContext时抛出

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

做了该错误的搜索导致我相信我需要在我的Global.asax的Application_Start方法下面一行:

System.Data.Entity.Database.SetInitializer<MyDBContext>(null); 

这是假设运行应用程序本身时,修复一个类似的错误。不幸的是,当我运行我的应用程序并且似乎没有为我的单元测试项目提供Application_Start方法时,我不会收到此错误。有没有办法到单元测试项目中使用自定义数据库后端并忽略其中发生的任何更改?

我在我的主项目上工作了一段时间之后添加了单元测试项目,所以有可能我搞砸了,但我无法弄清楚我该怎么做。我正在使用Visual Studio 2010中的内置单元测试。

回答

1

有两种方法可以与VS单元测试框架一起使用,从而允许您在每次测试之前和之后以及所有测试之前和之后运行一些代码包含在文件

// Use TestInitialize to run code before running each test 
[TestInitialize()] 
public void MyTestInitialize() 
{ 

} 

// Use TestCleanup to run code after each test has run 
[TestCleanup()] 
public void MyTestCleanup() 
{ 

} 

或:

// Use ClassInitialize to run code before running the first test in the class 
[ClassInitialize()] 
public static void MyClassInitialize(TestContext testContext) 
{ 

} 

// Use ClassCleanup to run code after all tests in a class have run 
[ClassCleanup()] 
public static void MyClassCleanup() 
{ 

} 
+0

谢谢。我在哪个文件中放置TestInitialize和TestCleanup方法? – Sparafusile 2012-07-17 12:17:22

+0

在你的单元测试中。 – 2012-07-17 13:05:25

+0

这些是可以放入每个单元测试类的方法。谢谢,那就是我需要知道的。 – Sparafusile 2012-07-18 21:52:34