将asp.net 5测试放在单独的程序集中

时间:2016-01-04 11:29:58

标签: unit-testing asp.net-core xunit

我使用Microsoft.AspNet.TestHost来托管xunit集成测试。只要测试与asp.net-5解决方案在同一个项目中,一切都可以正常工作 但我想将测试放入一个单独的程序集中,以便将它们与解决方案分开。但是当我尝试在单独的解决方案中运行测试时出现错误,TestServer无法找到视图。

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.

我猜测试服务器正在寻找相对于本地目录的视图。我怎样才能让它看到正确的项目路径呢?

4 个答案:

答案 0 :(得分:5)

我在这里有一个样本回购 - AutocompleteFilter.Builder显示修复(感谢David Fowler)。

TL; DR - 设置TestServer时,您需要设置应用程序基本路径以查看其他项目,以便查找视图。

答案 1 :(得分:2)

为了将来参考,请注意您现在可以像这样设置内容根目录:

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

答案 2 :(得分:1)

当RC1是当前版本时,写了Matt Ridgway的答案。现在(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位于测试程序集bin / debug / {platform-version} / {os-buildarchitecture} /文件夹中。您需要向上遍历该树,直到您到达包含您的视图的项目。就我而言。 SaasDemo.TestsSaasDemo.Web位于同一文件夹中,因此遍历5个文件夹的数量合适。

答案 3 :(得分:0)

为了让重写的启动类工作,我必须做的另一个更改是将IHostingEnvironment对象中的ApplicationName设置为Web项目的实际名称(Web程序集的名称)。

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

当TestStartup位于不同的程序集中并覆盖原始的Startup类时,这是必需的。在我的情况下仍然需要UseContentRoot。

如果没有设置名称,我总是找不到404。

相关问题