Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Is this a best-practice for application wide variable usage?</p> </blockquote> <p>Best practice is a bit of a subjective notion and without fully explaining your scenario and what precisely are you trying to achieve I prefer not to discuss it.</p> <p>We cannot discuss whether this is best practice but from what I can see it is not wrong either. It is not wrong because you are using the abstractions allowing the code to be unit tested.</p> <blockquote> <p>In the unit test, how can I add the application level variables the controller needs?</p> </blockquote> <p>You could use a mocking framework such as Rhino Mocks to mock the abstractions that the controller needs. Let's take as an example the following controller:</p> <pre><code>public class HomeController : Controller { public ActionResult Index() { var myVar = (MyVar)HttpContext.Application["MyVar"]; return Content(myVar.Foo); } } </code></pre> <p>and we would like to unit test the Index action. Here's a sample unit test:</p> <pre><code>[TestMethod] public void Index_Action_Should_Retrieve_MyVal_From_AppState() { // arrange var target = new HomeController(); var httpContext = MockRepository.GeneratePartialMock&lt;HttpContextBase&gt;(); var application = MockRepository.GeneratePartialMock&lt;HttpApplicationStateBase&gt;(); application.Expect(x =&gt; x["MyVar"]).Return(new MyVar { Foo = "bar" }); httpContext.Expect(x =&gt; x.Application).Return(application); target.ControllerContext = new ControllerContext(httpContext, new RouteData(), target); // act var actual = target.Index() as ContentResult; // assert Assert.AreEqual("bar", actual.Content); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload