3

for a unit test I am trying to add a value to the HttpApplicationState object, which is the Application property of the HttpContext.Current class. I try with the following code

        TextWriter tw = new StringWriter();
        HttpWorkerRequest wr = new SimpleWorkerRequest("/webapp", @"path...", "logon.asp", "", tw);

        HttpContext.Current = new HttpContext(wr);

        //I try the following 2 lines
        HttpContext.Current.Application["KeyValue"] = "myValue";
        HttpContext.Current.Application.Add("KeyValue", "myValue");

        var count = HttpContext.Current.Application.Count;
        var get1 = HttpContext.Current.Application["KeyValue"];
        var get2 = HttpContext.Current.Application.Get("KeyValue");

But HttpContext.Current.Application.Count is always zero. The values do not get

What am I doing wrong?

Bob
  • 4,236
  • 12
  • 45
  • 65

1 Answers1

0

Depending on the version of .NET you're targeting you might want to look into HttpContextBase and HttpContextWrapper. HttpContextBase is abstract so mocking frameworks like moq will allow you to assign its properties anyway you choose.

brianc
  • 1,547
  • 3
  • 16
  • 30
  • using .NET framework 3.5 actually. Those classes are for .NET 4 – Bob Nov 18 '10 at 12:45
  • ah you're correcct. Still having problems getting it working though. HttpContext doesn't inherit from HttpContextBase so i can't create my own class and use that instead or am I missing somehthing? – Bob Nov 18 '10 at 13:17
  • in your app you have to wrap the usage of HttpContext with HttpContextWraper(HttpContext.Current). The wrapper returns HttpContextBase – brianc Nov 18 '10 at 13:23
  • Yes it returns HttpContextBase which is not the same as type HttpContext as HttpContext does not inherit it. So i cannot use HttpContextWraper as a substitute for HttpContext i.e. i cannot do HttpContext.Current = HttpContextWraper which is what i want to do as the method i am testing, that cannot be refactored, uses HttpContext.Current.Application – Bob Nov 18 '10 at 13:46
  • ok, then you'd have to look into something like this http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx... – brianc Nov 18 '10 at 15:40