当前位置:  开发笔记 > 后端 > 正文

如何使用rhino mocks在MVC RC1中存根HttpSessionState?

如何解决《如何使用rhinomocks在MVCRC1中存根HttpSessionState?》经验,为你挑选了1个好方法。

我正在尝试利用asp.net mvc rc1中最近的ControllerContext重构.我应该能够简单地存根会话,但在运行以下代码时,我在第2行继续获得System.NullReferenceException:

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

我究竟做错了什么?

编辑:我刚刚确认我有这个帖子的最新版本的rhino.



1> zihotki..:

您还需要模拟HttpContext才能使其正常工作.我正在使用HttpContext的模拟:

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();
        _requestBase = MockRepository.GenerateStub();
        _responseBase = MockRepository.GenerateStub();
        _sessionStateBase = MockRepository.GenerateStub();
        _serverUtilityBase = MockRepository.GenerateStub();

        _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("a@a.a"),
                                                 new string[] {"Admin"});

    }
}

在测试的SetUp中,我创建了一个控制器的实例:

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

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

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

一切正常,我可以为会话和许多其他事情添加参数.希望这可以帮助.

推荐阅读
Chloemw
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有