问题描述
我正在尝试使用 Rhino.Mocks
来模拟一个 ControllerContext
对象,以访问我的控制器单元中的运行时对象,如用户、请求、响应和会话测试.我编写了以下方法以尝试模拟控制器.
I am trying to use Rhino.Mocks
to mock up a ControllerContext
object to gain access to runtime objects like User, Request, Response, and Session in my controller unit tests. I've written the below method in an attempt to mock up a controller.
private TestController CreateTestControllerAs(string userName)
{
var mock = MockRepository.GenerateStub<ControllerContext>();
mock.Stub(con =>
con.HttpContext.User.Identity.Name).Return(userName);
mock.Stub(con =>
con.HttpContext.Request.IsAuthenticated).Return(true);
var controller = CreateTestController(); // left out of example for brevity
controller.ControllerContext = mock;
return controller;
}
但是,我模拟的 ControllerContext 的 HttpContext
为空,并且我尝试访问 HttpContext.User
等会导致 System.NullReferenceException
.
However, the HttpContext
of my mocked ControllerContext is null and there my attempts to access HttpContext.User
etc. cause a System.NullReferenceException
.
我的嘲讽做错了什么?
推荐答案
我强烈建议您查看 MVCContrib.TestHelper 使用 Rhino.Mocks
并提供一种优雅的方式来测试您的控制器.您的测试可能如下所示:
I would strongly recommend you looking at MVCContrib.TestHelper which uses Rhino.Mocks
and provides an elegant way to test your controllers. Here's how your test might look like:
[TestClass]
public class UsersControllerTests : TestControllerBuilder
{
[TestMethod]
public void UsersController_Index()
{
// arrange
// TODO : this initialization part should be externalized
// so that it can be reused by other tests
var sut = new HomeController();
this.InitializeController(sut);
// At this point sut.Request, sut.Response, sut.Session, ... are
// stubed objects on which you could define expectations.
// act
var actual = sut.Index();
// assert
actual.AssertViewRendered();
}
}
这是一个单元测试 对于 控制器是我编写的 示例 ASP.NET MVC 应用程序的一部分.
And here's an unit test for a controller that is part of a sample ASP.NET MVC application I wrote.
这篇关于我如何使用 Rhino.Mocks 来模拟 ControllerContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!