Unit Testing ASP.NET Generic Handlers without using HttpWebRequest

五迷三道 提交于 2019-12-12 05:38:23

问题


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 makes HttpWebRequest 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.


回答1:


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);


来源:https://stackoverflow.com/questions/12560213/unit-testing-asp-net-generic-handlers-without-using-httpwebrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!