2016-01-04 21 views
3

我使用Microsoft.AspNet.TestHost來託管xunit集成測試。只要測試與asp.net-5解決方案在同一個項目中,一切都可以正常工作。
但我想將測試放入單獨的程序集中,以將它們與解決方案分開。但是當我嘗試在單獨的解決方案中運行測試時出現錯誤時,TestServer無法找到視圖。在單獨的程序集中放置asp.net 5測試

Bsoft.Buchhaltung.Tests.LoginTests.SomeTest [FAIL] 
    System.InvalidOperationException : The view 'About' was not found. The following locations were searched: 
    /Views/Home/About.cshtml 
    /Views/Shared/About.cshtml. 

我猜測測試服務器相對於本地目錄查看視圖。我怎樣才能讓它看到正確的項目路徑呢?

+0

您是否找到此解決方案 –

+0

不需要,我仍然需要一個解決方案:( – Sam

回答

1

馬特·李奇微的答案寫,當RC1是當前版本。現在(RTM 1.0.0/1.0.1),這已經變得簡單:

public class TenantTests 
{ 
    private readonly TestServer _server; 
    private readonly HttpClient _client; 

    public TenantTests() 
    { 
     _server = new TestServer(new WebHostBuilder() 
       .UseContentRoot(Path.GetFullPath(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "..", "..", "..", "..", "..", "SaaSDemo.Web"))) 
       .UseEnvironment("Development") 
       .UseStartup<Startup>()); 
     _client = _server.CreateClient(); 

    } 

    [Fact] 
    public async Task DefaultPageExists() 
    { 
     var response = await _client.GetAsync("/"); 

     response.EnsureSuccessStatusCode(); 

     var responseString = await response.Content.ReadAsStringAsync(); 

     Assert.True(!string.IsNullOrEmpty(responseString)); 

    } 
} 

關鍵的一點是這裏.UseContentRoot(Path.GetFullPath(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "..", "..", "..", "..", "..", "SaaSDemo.Web")))

的ApplicationBasePath是在您的測試組件斌/調試/ {平臺版本}/{os-buildarchitecture} /文件夾。您需要向上遍歷該樹,直到您到達包含視圖的項目。就我而言。 SaasDemo.TestsSaasDemo.Web位於同一個文件夾中,因此遍歷5個文件夾的數量是正確的。

+1

它不適用於我。建議可能的原因包括:在「buildOptions」下;在應用程序的project.json中缺少「preserveCompilationContext」屬性;但是它在我的.csproj中設置了一個或多個編譯引用。文件。 –

2

以供將來參考,請注意您現在可以設置內容根這樣的:

string contentRoot = "path/to/your/web/project"; 
IWebHostBuilder hostBuilder = new WebHostBuilder() 
    .UseContentRoot(contentRoot) 
    .UseStartup<Startup>(); 
_server = new TestServer(hostBuilder); 
_client = _server.CreateClient(); 
+0

在單獨的程序集中測試與測試,我的路徑是相對的,工作以及。謝謝: _server = new TestServer(new WebHostBuilder() .UseContentRoot(@「.. \ .. \ .. \ .. \ My.Real.Api」) .UseStartup ()); –

0

爲了使重寫的啓動類能夠工作,我必須做的另一項更改是將IHostingEnvironment對象中的ApplicationName設置爲Web項目的實際名稱(Web程序集的名稱)。

public TestStartup(IHostingEnvironment env) : base(env) 
     { 
      env.ApplicationName = "Demo.Web"; 
     } 

當TestStartup位於不同的程序集並覆蓋原始啓動類時,這是必需的。在我的情況下,UseContentRoot仍然是必需的。

如果沒有設置名稱,我總是找不到404。

相關問題