Owin Middleware不使用Test Server修改响应状态

时间:2016-11-21 20:10:06

标签: c# owin owin-middleware

我正在使用Owin Test Server编写单元测试,但它的行为并不像我期望的那样。我无法弄清楚我做错了什么。我希望状态代码已被修改,正如我在owin管道的最后一步中所做的那样,但它没有生效,因此第二个断言失败。

using Owin;
using Microsoft.Owin;
using Microsoft.Owin.Testing;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace My.Namespace
{
    [Trait("Category", "Test Category")]
    public class WhenIMakeWebRequest
    {
        [Fact]
        public async void IGetUnauthorizedError()
        {
            using (var server = TestServer.Create(app =>
            {
                app.Use((context, next) =>
                {
                    return next().ContinueWith(task =>
                    {
                        context.Response.WriteAsync(" Now Changing Status Code");
                        context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    });
                });
                app.Run(async context =>
                {
                    await context.Response.WriteAsync("Hello world using OWIN TestServer.");
                });
            }))
            {
                var response = await server.CreateRequest("/Welcome").GetAsync();
                var result = await response.Content.ReadAsStringAsync();
                Assert.Equal(result, "Hello world using OWIN TestServer. Now Changing Status Code");
                Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.Unauthorized);
            }

        }
    }
}

1 个答案:

答案 0 :(得分:0)

找到答案。实际上,在已经写出正文中的内容后,无法设置标题。所以我需要缓冲输出,以便设置标题。