0

I am trying to unit test HttpContext in my test class as follows, but could not find the way how to set request body for this object.

Is there any way to do it? So HttpContext.Current.Request.GetBufferedInputStream(); will return the bytes of the body string I set.

   [TestMethod()]
    public void GetRequestStringTest2()
    {
        string filename = "";
        string url = "http://www.localhost.com";
        string queryString = "";
        HttpRequest request = new HttpRequest(filename, url, queryString);
        // TODO: set request body here
        // string requestBody = "request-test-123";
        StringBuilder sb = new StringBuilder("response-test-123");
        StringWriter writer = new StringWriter(sb);
        HttpResponse response = new HttpResponse(writer);
        HttpContext.Current = new HttpContext(request, response);
        string requestString = HttpUtilities.GetRequestString();
        Assert.IsNotNull(requestString);
        Assert.AreEqual("request-test-123", requestString);
    }

 public static string GetRequestString()
        {
            if (HttpContext.Current != null)
            {
                Stream stream = HttpContext.Current.Request.GetBufferedInputStream();
                new StreamReader(stream).ReadToEnd();
                StreamReader bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
                bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
                string requestString = bodyStream.ReadToEnd();
                return requestString;
            }

            throw new InvalidOperationException("HttpContext.Current is not available.");
        }
Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158

1 Answers1

0

There is, but it will not be easy.

In order to do this you need to call the method internal void SetRawContent(HttpRawUploadedContent rawContent) from HttpRequest.

The problem is, you cannot call a internal method from a external assembly, however there is some ways to bypass this: C# - How to access internal class from external assembly.

Leonardo Menezes
  • 496
  • 5
  • 11