如何使用 moq 模拟 Controller.User

时间:2023-02-27
本文介绍了如何使用 moq 模拟 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.

我开始用这样的代码对这些方法进行测试

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?

推荐答案

你需要Mock ControllerContext、HttpContextBase,最后是IPrincipal来模拟Controller上的用户属性.使用 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.

这篇关于如何使用 moq 模拟 Controller.User的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何模拟没有接口的类? 下一篇:依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq)

相关文章

最新文章