views:

685

answers:

1

I'm trying to take advantage of the recent ControllerContext refactoring in asp.net mvc rc1. I should be able to stub the session rather simply but I keep getting a System.NullReferenceException on line 2 when running the following code:

var mockContext = MockRepository.GenerateStub<ControllerContext>();
mockContext.Stub(x => x.HttpContext.Session["MyKey"]).Return("MyValue");

What am I doing wrong?

Edit: I just verified I have the latest version of rhino as of this post.

+2  A: 

You need to mock HttpContext too to make this working. I'm using a mock of HttpContext for this:

public class HttpContextMock
{
    private readonly HttpContextBase _contextBase;
    private readonly HttpRequestBase _requestBase;
    private readonly HttpResponseBase _responseBase;
    private readonly HttpSessionStateBase _sessionStateBase;
    private readonly HttpServerUtilityBase _serverUtilityBase;

    public HttpContextBase Context { get { return _contextBase; } }
    public HttpRequestBase Request { get { return _requestBase; } }
    public HttpResponseBase Response { get { return _responseBase; } }
    public HttpSessionStateBase Session { get { return _sessionStateBase; } }
    public HttpServerUtilityBase Server { get { return _serverUtilityBase; } }


    public HttpContextMock()
    {
        _contextBase = MockRepository.GenerateStub<HttpContextBase>();
        _requestBase = MockRepository.GenerateStub<HttpRequestBase>();
        _responseBase = MockRepository.GenerateStub<HttpResponseBase>();
        _sessionStateBase = MockRepository.GenerateStub<HttpSessionStateBase>();
        _serverUtilityBase = MockRepository.GenerateStub<HttpServerUtilityBase>();

        _contextBase.Stub(x => x.Request).Return(_requestBase);
        _contextBase.Stub(x => x.Response).Return(_responseBase);
        _contextBase.Stub(x => x.Session).Return(_sessionStateBase);
        _contextBase.Stub(x => x.Server).Return(_serverUtilityBase);

        _requestBase.Stub(x => x.IsAuthenticated).Return(true);

        _contextBase.User = new GenericPrincipal(new GenericIdentity("[email protected]"),
                                                 new string[] {"Admin"});

    }
}

And in SetUp of test I create an instance of a controller:

    [SetUp]
    public override void TestSetUp()
    {
        base.TestSetUp();

        repository = MockRepository.GenerateMock<IFooRepository>();
        controller = new FooController()
                         {
                             FooRepository = repository,
                             UserRepository = userMockRepository
                         };

        controller.ControllerContext = new ControllerContext(context.Context, new RouteData(), controller);
    }

And all is working fine, I can add parameters to session and many other things. Hope this helps.

zihotki