0

I'm writing a unit test using Owin Test Server, but it is not behaving as I expect it to. I can't figure out what I'm doing wrong. I expect the status code to have been modified, as I'm doing in the last step of the owin pipeline, but it is not taking effect, and so the second assertion fails.

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);
            }

        }
    }
}
Asif Shiraz
  • 864
  • 1
  • 12
  • 27

1 Answers1

0

Found out the answer. Actually, headers cannot be set after content in body has already been written out. So I need to buffer the output, in order to set the headers.

Asif Shiraz
  • 864
  • 1
  • 12
  • 27