微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

单元测试 – 从TestServer测试asp.net 5 vnext中间件

在Owin中,可以使用TestServer在单元测试中测试web api(参见本 blog).

这个功能是否适用于asp.net 5中间件?

更新:

根据下面的回答,我尝试使用TestServer,但是visual studio抱怨’名称空间名称’AspNet’在名称空间’Microsoft’中不存在(你……)

>我使用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);
    }
}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐