2017-02-28 116 views
1

我試圖將單元測試添加到我的MVC應用程序。具體來說,我目前正在嘗試測試Web API控制器的某些部分。爲控制器單元測試配置實體框架

當我的測試方法試圖實際加載控制器時,我得到一個錯誤,指出我沒有定義所需的數據庫連接字符串。

即使連接字符串在我的主項目中定義,我知道我需要將它們添加到我的測試項目的app.config,我這樣做。但後來我得到了一個新的錯誤。

VegaModel.ssdl(2,2) : error 0152: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file.

我沒有得到這個錯誤,但建議的修復似乎很容易,我複製從我的web.config<entityFramework>節我的測試項目的的app.config

現在我得到這個錯誤:

Unrecognized configuration section entityFramework. (C:\Users\Jonathan\Documents\Viper\Branches\Vega\Vega.Tests\bin\Debug\Vega.Tests.dll.config line 38)

好吧,好吧,那最後兩個錯誤似乎相互矛盾。但更重要的是,我的主程序使用實體框架,但我的測試項目不(至少)。所以我對這條道路感到困惑,這似乎導致越來越多的在我的測試項目中配置的實體框架。

什麼是能夠加載從單元測試項目使用實體框架的控制器的最簡方法?

+1

您的實體框架部分對於副本無效,爲什麼您要手動執行此操作,爲什麼不使用nuget在單元測試項目中安裝適當版本的EF並讓它添加配置 –

+4

聽起來像您需要考慮嘲笑 – mrfreester

+0

@ johnny5:我想我沒有完全理解爲什麼我需要在我的測試項目中使用Entity Framework。但我想在這種情況下,主應用程序不運行,而是我只是在我的測試應用程序中加載一個類。所以,我想我會嘗試你的建議。但是,這使我想知道我還需要安裝什麼。一切安裝在我的主應用程序? –

回答

2

雖然這聽起來更像一個集成測試比單元測試中,該第二誤差

Unrecognized configuration section entityFramework.

是因爲,從配置文件中的頂部缺少下列。

<configuration> 
    <configSections> 
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> 
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> 
    </configSections> 
    <!--other sections removed for brevity --> 
    <entityFramework> 
    <!-- removed for brevity --> 
    </entityFramework> 
</configuration> 

即一旁,指示

So I'm troubled about this path that seems to lead towards getting more and more of Entity Framework configured in my test project.

一個建議是抽象掉緊耦合到實體框架,使得控制器可以在單元隔離經由這些依賴關係的嘲笑測試。