0

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 1

2

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.