如何嘲笑Controller.User使用最小起订量 [英] How to mock Controller.User using moq

查看:160
本文介绍了如何嘲笑Controller.User使用最小起订量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个ActionMethods的一个查询Controller.User像这样它的作用

I have a couple of ActionMethods that queries the Controller.User for its role like this

bool isAdmin = User.IsInRole("admin");

根据这一条件方便行事。

acting conveniently on that condition.

我开始作出这些方法code这样的

I'm starting to make tests for these methods with code like this

[TestMethod]
public void HomeController_Index_Should_Return_Non_Null_ViewPage()
{
    HomeController controller  = new HomePostController();
    ActionResult index = controller.Index();

    Assert.IsNotNull(index);
}

和测试失败,因为Controller.User未设置。
任何想法?

and that Test Fails because Controller.User is not set. Any idea?

推荐答案

您需要模拟ControllerContext,HttpContextBase最后的IPrincipal嘲笑控制器上的用户属性。使用MOQ(V2)的东西沿​​着以下行应该工作。

You need to Mock the ControllerContext, HttpContextBase and finally IPrincipal to mock the user property on Controller. Using Moq (v2) something along the following lines should work.

    [TestMethod]
    public void HomeControllerReturnsIndexViewWhenUserIsAdmin() {
        var homeController = new HomeController();

        var userMock = new Mock<IPrincipal>();
        userMock.Expect(p => p.IsInRole("admin")).Returns(true);

        var contextMock = new Mock<HttpContextBase>();
        contextMock.ExpectGet(ctx => ctx.User)
                   .Returns(userMock.Object);

        var controllerContextMock = new Mock<ControllerContext>();
        controllerContextMock.ExpectGet(con => con.HttpContext)
                             .Returns(contextMock.Object);

        homeController.ControllerContext = controllerContextMock.Object;
        var result = homeController.Index();
        userMock.Verify(p => p.IsInRole("admin"));
        Assert.AreEqual(((ViewResult)result).ViewName, "Index");
    }

测试时的行为的用户不是管理员是在更换期望的userMock对象上设置返回false一样简单。

Testing the behaviour when the user isn't an admin is as simple as changing the expectation set on the userMock object to return false.

这篇关于如何嘲笑Controller.User使用最小起订量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆