2011-09-12 42 views
2

我正在學習VS2010中的單元測試功能中構建的微軟,並遇到了一個問題。單元測試MVC 3和實體框架

[TestClass] 
public class HomeControllerTest 
{ 

    [TestMethod] 
    public void SomeTest() 
    { 
     //Arrange 
     HomeController controller = new HomeController(); 


     //Act 
     ViewResult results = controller.Index() as ViewResult; 

     //Assert 
     ViewDataDictionary viewData = results.ViewData; 

     Assert.AreEqual(null, viewData["Message"]); 

    } 
} 

我知道這將返回失敗,這不是一個問題。但是,什麼是問題是我打我的EntityFramework模型「myModel.edmx」並得到錯誤"System.ArgumentException: The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid."

這是在文件MyModel.Designer.cs中。有問題的線是:

public Tool_Entities() : base("name=Tool_Entities", "Tool_Entities") { this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated(); } 我知道這條線是好的,因爲當我運行非測試項目,我可以連接到這個模型罰款。

+0

看看這篇文章:http://bit.ly/bF7jL3。它解釋瞭如何圍繞您的O/RM構建(啓用LINQ)抽象。 – Steven

+0

你的測試是在一個單獨的項目中嗎? (在這種情況下,測試運行自己的app.config) –

回答

3

您應該以面向服務或存儲庫的方式將EF從控制器中抽象出來。這樣你就可以去除你的單元測試的依賴關係(並且注入一個模擬)並測試你的控制器。

首先創建一個接口。這只是一個藍圖,你可以讓它成爲你想要的方式。

public interface IToolRepository 
{ 
    void Add(Tool something); 
    IQueryable<Tool> Query { get; } 
    void Delete(Tool something); 
} 

然後用EF實現這個。

+0

我該怎麼做呢?我對EntityFramework相當陌生。 我想我將不得不以某種方式爲EF模型創建接口? – JustAnotherDeveloper