Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a HttpContext for testing, how can I specify the HttpRequest is a POST?

I'm writing some unit tests for a method that takes an HttpContext as a parameter. I want to test that the behavior is as expected when the request is a POST.

When creating a System.Net.HttpWebRequest it's easy to set the method, but I can't see a way to specify the method when creating a System.Web.HttpRequest which is what's used in HttpContext.

Any ideas?

For context the method is called by an httphandler and it is supposed to throw a 405 if the request is not a POST. I know that I can filter the allowable methods with the Verbs property in the web.config, and I will, however there's nothing stopping somebody in the future from changing the verbs property to allow other methods in which case I want the handler to take care of it itself.

Helper method currently in use:

    private HttpContext GetHttpContext(string requestUrl)
    {
        var httpRequest = new HttpRequest("", requestUrl, "");            
        var stringWriter = new StringWriter();
        var httpResponce = new HttpResponse(stringWriter);
        return new HttpContext(httpRequest, httpResponce);
    }
like image 714
mdchris Avatar asked Dec 03 '12 22:12

mdchris


1 Answers

I would recommend researching mocking objects for the purpose of unit testing. There are a few mocking frameworks available for .NET that facilitate exactly this type of test.

For example, the article here sets the HttpMethod using the Moq framework.

From the article:

public ContextMocks(Controller onController, string HTTPMethod)
{
    //...
    Request = new Moq.Mock<HttpRequestBase>();
    Request.Setup(x => x.HttpMethod).Returns(HTTPMethod);
    //...
}

That said, if this is a one-off test, and I can't stress that enough, and the overhead incurred by introducing object mocking is unnecessary in your particular situation, the following reflection will set the HttpMethod:

typeof(HttpRequest).GetField("_httpMethod", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(httpRequest, "POST");

As I mentioned previously, if testing with HttpContext, HttpRequest, etc. are or will become a recurring theme, then take advantage of a mocking framework. You will save yourself time in the long run.

like image 67
cokeman19 Avatar answered Sep 30 '22 00:09

cokeman19