2015-06-25 72 views
2

我想測試我的MVC項目。爲了簡單起見,在Startup I類有:Startup.cs不是解僱

public static IConfiguration Configuration { get; set; } 

public Startup(IHostingEnvironment env) 
{ 
    // Setup configuration sources. 
    var configuration = new Configuration() 
     .AddJsonFile("config.json"); 

    Configuration = configuration; 
} 

,我使用這個配置全球範圍內,像這樣:

private static string connectionString = Startup.Configuration["Database:ConnectionString"]; 

它的工作原理,它可以在文件中找到。

我的問題:

當我運行測試,Startup類似乎不被解僱。因爲無論何時我訪問Startup.Configuration,此字段爲空

我能做些什麼來啓動它,以便讀取config.json文件?或者我可以如何解決這個問題?

回答

1

當您啓動Web服務器時,通常會調用啓動方法,無論它是IIS Express,Web Listener,Kestrel等。如果您嘗試運行測試,則需要啓動服務器或測試服務器,然後調用你的啓動方法。

Microsoft.AspNet.TestHost是用於創建基於測試的服務器的好工具。特別是TestServer我在這裏講的生活:https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.TestHost/TestServer.cs

下面是我們如何使用它在MVC: https://github.com/aspnet/Mvc/blob/dev/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs
和實際測試創建服務器
https://github.com/aspnet/Mvc/blob/cc4ee1068de55a0948c35f5a87f6c05907cb8461/test/Microsoft.AspNet.Mvc.FunctionalTests/DefaultValuesTest.cs#L42

希望這有助於!