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