tiagodaraujo / HttpContextMoq

MIT License
34 stars 14 forks source link

how to set request body? #2

Closed juleedev closed 2 years ago

juleedev commented 2 years ago

I'm trying to figure out how to use this library as a part of my unit testing. Likely my problem is my limited knowledge of c# and moq so I apologize in advance if this is a noob question.

I need to create a fake http request with 2 things - a body and a specific item in the HttpContext.Items dictionary. Neither one is being set correctly.

Here's the code:

private static HttpRequest CreateHTTPPostRequest(object body)
    {
        var mockRequest = new HttpContextMock(); 
        mockRequest.Request.HttpContext.Items.Add("MS_AzureFunctionsRequestID",123123123);

        var ms = new MemoryStream();
        var sw = new StreamWriter(ms);

        var json = JsonConvert.SerializeObject(body);

        sw.Write(json);                        
        sw.Flush();

        ms.Position = 0;

        mockRequest.Request.Body = ms;      
        return mockRequest.Request;
    }

I dont' get any errors but the body isn't being set correctly. In my debug window, if I try this:

   mockRequest.Request.HttpContext.Items.Count

it returns 0 and also the body is null.

I'm reviewing the sample code but I haven' been able to find what I'm looking for yet.