c# - ASP.Net Core 集成测试

标签 c# asp.net-core integration-testing

我正在努力获得与 ASP.Net Core RC2 一起使用的任何类型的集成测试。 我创建了一个基本的 Web 项目,它在浏览器中运行良好,显示了预期的默认页面。然后我使用以下测试代码添加了一个新类(在同一个项目中):

[TestClass]
public class HomeControllerTests
{
    private HttpClient client;

    [TestInitialize]
    public void Initialize()
    {
        // Arrange
        var host = new WebHostBuilder()
           .UseEnvironment("Development")
           .UseKestrel()
           .UseContentRoot(Directory.GetCurrentDirectory())
           .UseIISIntegration()
           .UseStartup<Startup>();

        TestServer server = new TestServer(host);

        client = server.CreateClient();
    }


    [TestMethod]
    public async Task CheckHomeIndex()
    {
        string request = "/";

        var response = await client.GetAsync(request);

        response.EnsureSuccessStatusCode();

        Assert.IsTrue(true);
    }
}

测试未通过,但有以下异常:

The view 'Index' was not found. The following locations were searched:
/Views/Home/Index.cshtml
/Views/Shared/Index.cshtml

在此阶段,我使用的是 MSTest 而不是 xUnit。不幸的是,将 ContentRoot 更改为“重复”问题中建议的内容并不能解决问题。

有人进行集成测试吗?我试过调整 WebHostBuilder 设置,但没有成功。

最佳答案

我写了一篇关于集成测试的博文(不涉及 MVC),“Snow Crash”评论了类似的问题。他们使用以下代码解决了“未找到”错误:

var path = PlatformServices.Default.Application.ApplicationBasePath;
var setDir = Path.GetFullPath(Path.Combine(path, <projectpathdirectory> ));

var builder = new WebHostBuilder()
   .UseContentRoot(setDir)
   .UseStartup<TStartup>();

博文在这里Introduction to integration testing with xUnit and TestServer in ASP.NET Core .

关于c# - ASP.Net Core 集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37831061/

相关文章:

c# - C# 中的简单条形图

MySql:当外表中没有对应的行时,使用 INNER JOIN 删除一行

c# - MemoryStream 不包含 GetBuffer() 的定义

asp.net-core - 将服务单例注入(inject) ASP.NET Core 中的 actor (Akka.NET)

asp.net-mvc - 有人用过 Steve Sanderson 的 MvcIntegrationTestFramework 吗?

c# - 旋转大量 Timers.Timer 线程

c# - 这种类型的委托(delegate)叫什么(C#)

c# - 无法从动态创建控件中读取值

java - 如何测试 gRPC(功能和集成测试)

ruby-on-rails - 如何为 Rails 中的集成测试编写帮助程序?