本文介绍了如何使用Rhino.Mocks嘲弄一个ControllerContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 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 我的嘲笑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();
    }
}

这是一个unit测试的controller这是我写了一个样本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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!