如何使用 moq 模拟 Controller.User

How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
本文介绍了如何使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How do I mock a class without an interface?(如何模拟没有接口的类?)
Mocking Static methods using Rhino.Mocks(使用 Rhino.Mocks 模拟静态方法)