Pete
Pete

Reputation: 10871

Unit testing with dependency on HttpContext

I need to test some static methods that rely on the current context. Now, I can certainly use the HttpContextWrapper to remove this dependency from my own code. The problem lies with the 3rd party API I am using in these methods. THEY are relying on the HttpContext and so I can't do anything about that. However, what I'm trying to do is set the HttpContext with my HttpContextBase.

So my code looks something like this:

public static bool IsSignedUpUser()
{
    //This calls IsSignedUpUser with the production context
    return IsSignedUpUser(new HttpContextWrapper(HttpContext.Current));
}

public static bool IsSignedUpUser(HttpContextBase context)
{
    HttpCookie objCookie = SomeExternalAPIThatReliesOnHttpContextBeingSet();

    return (objCookie != null)
}

What I want to do is something like:

HttpContext.Current = context; //where context is a mocked HttpContextBase

This way when the 3rd party API is looking in the HttpContext for querystring, cookie values, etc, it doesn't throw a NullReferenceException.

Why isn't this a dupe?

In the code in the question referenced as a dupe, the author looks to be in complete control with no external dependencies. I'm using third party libraries that have a dependency on HttpContext, I can't change their method signatures to accept HttpContextBase so I need a way to assign my HttpContextBase to HttpContext.

If this is not possible, and so far I am lead to believe that it isn't, then good answers should suggest how to remove these dependencies. 500 - Internal Server Error has at least one good suggestion.

Upvotes: 2

Views: 725

Answers (2)

In my view, you should be replacing the call to SomeExternalAPIThatReliesOnHttpContextBeingSet with a custom interface method that you inject and which can then be mocked as any other.

Upvotes: 4

JerKimball
JerKimball

Reputation: 16894

[EDIT] Per @jessehouwing, "Moles" is now "Fakes", which should improve your Google-fu

Ah, static dependencies...the worse kind.

It may be overkill, but I would look into perhaps using Moles (or whatever the heck they renamed it to), which will let you override ANY behavior, static, sealed or otherwise; here are some links to peruse:

Upvotes: 2

Related Questions