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