您也需要模拟 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"});
}
}
在测试设置中,我创建了一个控制器实例:
[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);
}
一切正常,我可以向会话和许多其他东西添加参数。希望这可以帮助。