Unit Test Controller Session Variables in MVC3

I am testing my controller module.

In one of my controller methods, I set session variables:

public void Index(){ Session["foo"] = "bar"; return View(); } 

How can I unit test this? The problem is that the Session property is null during testing. Injection is not possible because the Session property is read-only.

  [TestMethod] public void TestIndex() // When _controller.Index(); // Then Assert.AreEqual("bar", _controller.Session["foo"]) 
+4
source share
3 answers

Personally, I like to use the MvcContrib TestHelper , which mocks the entire HTTP pipeline:

 [TestMethod] public void HomeController_Index_Action_Should_Store_Bar_In_Session() { // arrange var sut = new HomeController(); new TestControllerBuilder().InitializeController(sut); // act sut.Index(); // assert Assert.AreEqual("bar", (string)sut.Session["foo"]); } 
+7
source

This is what I used for Unit Test friendly session caching. By checking HttpContext.Current for null, you pass caching for nunit tests and still allow your program to function normally.

This is the simplest solution without making a lot of code changes to your project.

 internal class SessionCache { public static void Store(string key, object val) { if (HttpContext.Current != null) { HttpContext.Current.Session[key] = val; } } public static object Retrieve(string key) { if (HttpContext.Current != null) { return HttpContext.Current.Session[key]; } return null; } } 
+3
source

I always recommend deforming the session object into another object. this not only gives you an easier way to test, but also makes all access to the session type safe, it is very easy to enter the name of the session key in one place in one place, and then quickly find the error. the object will have fields like

 public Foo{ get{return Session["Foo"];} set{Session["Foo"]=value;} } 

Once you test, you can mock a session class with a dummy that retains state only for the test. The way I usually deal with this is to inject dependency. How to fix this is a lengthy exam. Here is a link to one path http://weblogs.asp.net/shijuvarghese/archive/2011/01/21/dependency-injection-in-asp-net-mvc-3-using-dependencyresolver-and-controlleractivator.aspx

+2
source

All Articles