aspnet/AspNetWebStack

Using SelfHost in unit test fails because BufferedOutputStream closes before it is read

GRSuggitt opened this issue · 4 comments

I have a controller that returns a bunch of data.

The controller does work correctly when called with a web request across the internet.

I want to create unit tests for the controller and so I am using System.Web.Http.SelfHost to house the controller and tests which use HttpClient to make requests. But when I make a request to return data from the controller, I get an exception of the nature "connection was terminated unexpectedly".

The controller uses a formatter derived from System.Net.Http.Formatting.MediaTypeFormatter to produce the data to be returned.

The MediaTyepFormatter's WriteToStreamAsync function is overwritten. This function passes a Stream for the function to write into.

In the course of doing its work, the formatter creates a StreamWriter that overlays the given stream.

        public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            using (var writer = new StreamWriter(writeStream, SelectCharacterEncoding(content.Headers)))
            {
               // stuff written into stream
            }

When the writer is disposed, the underlying stream is closed.

That is when System.Web.Http.SelfHost\ServiceModel\Channels\BufferedOutputStream.Close() is called. Close calls Clear() and Clear sets _initilized to false.

But this occurs BEFORE the data is read from the buffer with the ToArray function.

I have added a small delay in Close() and now it works for me.

            Threading.Tasks.Task.Delay(100).ContinueWith( t => Clear() );

But there must be a better way.

@GRSuggitt thank you for your feedback. We're closing this issue as the questions asked here have been answered. Feel free to reopen the issue or create a new one if you have further questions.

Sorry, I meant leaveOpen = true