Unit Testing ASP.NET Generic Handlers without using HttpWebRequest
-
03-07-2021 - |
Question
I need to create Unit test cases for my ASP.NET generic Handler. My Handler code is as below:
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
var data = context.Request.InputStream;
//Here logic read the context.Request.InputStream
//All the data will be posted to this Stream
//Calling of business logic layer Methods
}
public bool IsReusable
{
get
{
return false;
}
}
}
Now, I need to create the Unit test cases for this Handler. I have tried following ways to do unit test cases.
- Making an
HttpWebRequest
to this handle and writing all the data to request stream. I don't want to proceed with this as we have separate tool which makesHttpWebRequest
to test all handlers - Creating Unit test cases for Business methods but in this i am unable to check some logic written in handler level.
I have tried to Mock the HttpContext but it's not allowing to mock this (is it possible to to Mock HttpContent?). I tried
this way but this needs modification to my handler also but i don't have provision to do this.
Finally my questions is, Is there any other way to unit test handler?
Thanks in Advance.
Solution
What you can do to mock the context is to create an additional method that uses an HttpContextBase and just forward a call from the interface method. The HttpContextBase can called using an HttpContextWrapper which would give you the possibility to mock the context
public void ProcessRequest(HttpContext context)
{
ProcessRequestBase(new HttpContextWrapper(context));
}
public void ProcessRequestBase(HttpContextBase ctx)
{
}
Which could be tested by hitting the ProcessRequestBase-method. We would have to assume that the ProcessRequestBase works as intended, but that's hard to avoid. Then you can test it using calls like this
HttpContextBase mock = new Mock<HttpContextBase>(); //or whatever syntax your mock framework uses
handler.ProcessRequest(mock.Object);