Farhad-Taran
Farhad-Taran

Reputation: 6512

Unit Testing Webform HttpContext Dependent code?

Im trying to write some unit tests for a couple of merthods that are dependant on the HttpContext object. I have come up with the following class but I dont think its the best way to do it.

internal class HttpContextMocking
{

    public static HttpContext Context()
    {

        HttpContext context = new HttpContext(new SimpleWorkerRequest("", "", "", null, new StringWriter()));

        context.Cache.Insert("SomeName", "value", null, DateTime.Now.AddMinutes(3), TimeSpan.Zero);

        return context;
    }

I then call this mock HttpContext in my unit test in the following way:

    [TestMethod]
    [TestCategory("Web")]
    public void Get()
    {
        HttpContext.Current = HttpContextMocking.Context();

        object result = CacheUtility.Get("NonExistentItem");

        Assert.IsNull(result);
    }

is there a better way of implementing this, something that would be cleaner when I start to add more dummy data.

Upvotes: 1

Views: 1337

Answers (2)

graham mendick
graham mendick

Reputation: 1839

The HttpContextWrapper and HttpContextBase .NET classes were created for mocking purposes e.g. http://www.codemerlin.com/2011/07/mocking-httpcontext-httpresponse-httprequest-httpsessionstate-etc-in-asp-net/

Upvotes: 1

Ivo
Ivo

Reputation: 8352

HttpContext is really complex to mock. I will suggest to change the dependency to an interface that provides what you need, and then have two implementations: a real one, using HttpContext and a Mock one for the tests.

If you anyway want to mock it and your code does the trick, leave it that way.

Another option is to use the ASP.NET host type for MSTest. In this case, you will be performing an actual request and your HttpContext will be there:

[TestMethod]
[HostType("ASP.NET")]
[AspNetDevelopmentServerHost(@"$(SolutionDir)\Tests", "/")]
[UrlToTest("http://localhost:1234/TestPage.aspx")]
public void MyTest()
{
    Page page = testContextInstance.RequestedPage;
    ...
}

Upvotes: 1

Related Questions