gpt4 book ai didi

asp.net-mvc - 如何使用犀牛模拟在 MVC RC1 中 stub HttpSessionState?

转载 作者:行者123 更新时间:2023-12-04 18:33:29 26 4
gpt4 key购买 nike

我正在尝试利用 recent ControllerContext refactoring在 asp.net mvc rc1 中。我应该能够相当简单地 stub session ,但在运行以下代码时,我在第 2 行不断收到 System.NullReferenceException:

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

我究竟做错了什么?

编辑:我刚刚确认我拥有这篇文章的最新版本的犀牛。

最佳答案

您也需要模拟 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<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("a@a.a"),
new string[] {"Admin"});

}
}

在设置测试中,我创建了一个 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);
}

一切正常,我可以向 session 和许多其他事情添加参数。
希望这可以帮助。

关于asp.net-mvc - 如何使用犀牛模拟在 MVC RC1 中 stub HttpSessionState?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/587179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com