I need to create a unit test stratergy for my application. In my ASP.NET MVC applicationI will be using session, now i need to know how to unit test my Action that uses Session.. I need to know if there are framework for unit testing action method involving Sessions.
1 Answer
If you need to mock session, you are doing it wrong :) Part of the MVC patters is that action methods should not have any other dependencies than parameters. So, if you need session, try "wrap" that object and use model binding (your custom model binder, binding not from POST data, but from session).
Something like this :
public class ProfileModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.Model != null)
throw new InvalidOperationException("Cannot update instances");
Profile p = (Profile)controllerContext.HttpContext.Session[BaseController.profileSessionKey];
if (p == null)
{
p = new Profile();
controllerContext.HttpContext.Session[BaseController.profileSessionKey] = p;
}
return p;
}
}
dont forget to register it while application start, and than you could use it like this :
public ActionResult MyAction(Profile currentProfile)
{
// do whatever..
}
nice, fully testable, enjoy :)