The Inquisitive Coder
The Inquisitive Coder

Reputation: 1315

Setting up HttpContext for .Net Unit Tests

I'm writing an unit test(using NUnit & MOQ) for an action method MethodUnderTest which uses HttpContext internally to do some functionality. I'm setting up a fake hosting environment by calling InitializeHostingEnvironment where I'm initializing the session like:

public static HttpSessionState InitializeSession()
{
    var httpRequest = new HttpRequest("", "http://localhost/", "");
    var stringWriter = new StringWriter();
    var httpResponse = new HttpResponse(stringWriter);
    var httpContext = new HttpContext(httpRequest, httpResponse);

    HttpContext.Current = httpContext;
    HttpContext.Current.Items.Clear();
    HttpSessionState session = (HttpSessionState)ReflectionHelper.Instantiate(typeof(HttpSessionState), new Type[] { typeof(IHttpSessionState) }, new FakeHttpSessionState());

    HttpContext.Current.Items.Add("AspSession", session);

    return session;
}

public static void InitializeHostingEnvironment(string userName, string password)
{
     // lines of code
     InitializeSession();
}

I'm calling the InitializeHostingEnvironment() from my Test Method like so:

public static void Test_MethodUnderTest()
{
    InitializeHostingEnvironment(UN, PW);
    MethodUnderTest(param1, param2, param3); -- getting exception while trying to execute this line
}

While trying to execute the line MethodUnderTest(param1, param2, param3);, I'm getting an exception - System.ArgumentNullException - Value cannot be null. Parameter name httpBrowserCapabilities. Stack trace is given below: enter image description here

Since the exception says httpBrowserCapabilities is null, I tried to initialize it like HttpContext.Current.Request.Browser = new HttpBrowserCapabilities(); inside the InitializeSession() method, but now, I'm getting another exception: enter image description here

What should I do now? Is the way I'm initializing HttpContext wrong? please advise.

Upvotes: 0

Views: 1281

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89416

I'm writing an unit test(using NUnit & MOQ) for a method MethodUnderTest which uses HttpContext internally to do some functionality.

Right. Don't do that. The controller should be the only method that accesses the HttpContext, and it should extract the data needed for your MethodUnderTest and use the to write to the HttpContext.

Structuring your code so that each method has a single responsibility is fundamental to writing testable code.

Upvotes: 4

Related Questions