title: How to use Rhino Mocks to Mock an HttpContext.Application
body: <p>I'm new to Mocking frameworks and have started using RhinoMocks to assist with my MVC App Unit Testing.</p>
  
  <p>I'm using <a href="http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx" rel="noreferrer">Scott Hanselmanns MVC Mock Helper</a> to assist in mocking the HttpContext.
  I've succesfully (after some time) mocked some of what I need but have come unstuck when it comes to the Application property of the HttpContext.</p>
  
  <p>In my application I store an object in the Application and retrieve it within a Controller like:</p>
  
  <pre><code>SomeObj foo = (SomeObj)Application["fooKey"];
  </code></pre>
  
  <p>This gets created on Application_Start in my MVC App.</p>
  
  <p><strong>UPDATED FOLLOWING FIRST ANSWER</strong> (additional code for clarity)
  Currently in the test setup I do:</p>
  
  <pre><code>HttpContextBase mockHttpBase = mocks.FakeHttpContext();
  controllerToTest = new SomeController();
  mocks.SetFakeControllerContext(controllerToTest);
  
  
  HttpApplicationStateBase appState = 
      MockRepository.GenerateStub&lt;HttpApplicationStateBase&gt;();
  
  Globals tmpAppGlobals = 
      new Globals();
  
  mockHttpBase.Expect(ctx =&gt; ctx.Application).Return(appState);
  mockHttpBase.Expect(ctx =&gt; ctx.Application[Globals.GlobalsKey]).
      Return(tmpAppGlobals);
  </code></pre>
  
  <p>In my unit test setup I do:</p>
  
  <pre><code>Globals tmpAppGlobals = new Globals();
  controllerToTest.ControllerContext.HttpContext.
              Expect(ctx =&gt; ctx.Application[Globals.GlobalsKey]).
  Return(tmpAppGlobals);
  </code></pre>
  
  <p>This call throws a NullReference Exception, for the Application object.</p>
  
  <p>My question is two fold:</p>
  
  <p>1) Is this the right approach or have I done something wrong from a design / architecture perspective?</p>
  
  <p>2) Why doesn't this work?!</p>
  
  <p>Thanks, in advance.</p>