0

I am writing a test that uses DefaultHttpContext in its call (startup is the test subject here):

[Fact]
public async void HandleCabinet_ShouldReturnValidCabinetSettings()
{
    var startup = new Startup();
    var context = DefaultHttpConext();

    await startup.HandleCabinet(context);

    string body;
    using (var reader = new StreamReader(context.Response.Body, Encoding.UTF8))
    {
        body = reader.ReadToEnd();
    }

    Assert.Equal("some expectation", body);
}

The problem is, body is always an empty string. In the HandleCabinet method, I write something into it like this:

await context.Response.WriteAsync("some expectation");

I saw by default, Body is a NullStream, so I tried setting a stream like this:

context.Response.Body = new BufferedStream(new MemoryStream());

but, that has no effect.

So, how can I construct the DefaultHttpContext, such that I can test the response?

Julian
  • 33,915
  • 22
  • 119
  • 174
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195

1 Answers1

1

You could use a MemoryStream and reset the position to 0.

e.g.

Creating the DefaultHttpContext:

private DefaultHttpContext CreateHttpContext()
{
    var context = new DefaultHttpContext
    {
        Response =
        {
            Body = new MemoryStream()
        }
    };
    return context;
}

Body to string: (note: C# 9 syntax)

public static string StreamToString(Stream stream)
{
    stream.Position = 0;
    using StreamReader reader = new(stream, Encoding.UTF8);
    return reader.ReadToEnd();
}

The assertion:

var body = StreamToString(context.Response.Body);
Assert.Equal("some expectation", body);

The setup I use for creating the DefaultHttpContext

Julian
  • 33,915
  • 22
  • 119
  • 174