问题描述
我试图使用 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;
}
但是, HttpContext
我的mocked ControllerContext是null,我试图访问 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
.
我的嘲笑我做错了什么?
What am I doing wrong with my mocking?
推荐答案
强烈建议您查看使用 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();
}
}
这是一个 ,它是我写了。
And here's an unit test for a controller that is part of a sample ASP.NET MVC application I wrote.
这篇关于如何使用Rhino.Mocks来模拟ControllerContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!