加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 03:38:21 所属栏目:asp.Net 来源:网络整理
导读:在Owin中,可以使用TestServer在单元测试中测试web api(参见本 blog). 这个功能是否适用于asp.net 5中间件? 更新: 根据下面的回答,我尝试使用TestServer,但是visual studio抱怨’名称空间名称’AspNet’在名称空间’Microsoft’中不存在(你……) 我使用Visu
在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课程用法的更多信息.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读