gpt4 book ai didi

unit-testing - 从 TestServer 测试 asp.net 5 vnext 中间件

转载 作者:行者123 更新时间:2023-11-28 19:48:18 25 4
gpt4 key购买 nike

在 owin 中,可以使用 TestServer 在单元测试中测试 web api(参见 blog)。

此功能可用于 asp.net 5 中间件吗?

更新:

根据下面的回复,我尝试使用 TestServer,但 visual studio 提示说'The type or namespace name 'AspNet' does not exist in the namespace 'Microsoft' (are you .....'

  • 我使用 Visual Studio 2015

  • 在我的 nuget 源(设置)中,我有 ( https://www.myget.org/F/aspnetmaster/ )(我也试过 https://www.myget.org/F/aspnetvnext/ ,但遇到了同样的问题)

  • 这是我的 project.json 文件

    {
    "version": "1.0.0-*",
    "dependencies": {
    "Microsoft.AspNet.Http": "1.0.0-*",
    "Microsoft.AspNet.TestHost": "1.0.0-*",
    "Microsoft.AspNet.Hosting": "1.0.0-*",
    "Microsoft.AspNet.Testing" : "1.0.0-*",
    "xunit": "2.1.0-beta1-*",
    "xunit.runner.aspnet": "2.1.0-beta1-*",
    "Moq": "4.2.1312.1622",
    "Shouldly": "2.4.0"
    },
    "commands": {
    "test": "xunit.runner.aspnet"
    },
    "frameworks" : {
    "aspnet50" : {
    "dependencies": {
    }
    }
    }
    }

最佳答案

它也适用于 ASP.NET 5:Microsoft.AspNet.TestHost .

这是一个示例。中间件:

public class DummyMiddleware
{
private readonly RequestDelegate _next;

public DummyMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext context)
{
Console.WriteLine("DummyMiddleware");
context.Response.ContentType = "text/html";
context.Response.StatusCode = 200;

await context.Response.WriteAsync("hello world");
}
}

测试:

[Fact]
public async Task Should_give_200_Response()
{
var server = TestServer.Create((app) =>
{
app.UseMiddleware<DummyMiddleware>();
});

using(server)
{
var response = await server.CreateClient().GetAsync("/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}

您可以找到有关 TestServer 用法的更多信息在 the tests 上课.

关于unit-testing - 从 TestServer 测试 asp.net 5 vnext 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29561277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com