How to mock Controller.User using moq

后端 未结 3 1416
陌清茗
陌清茗 2020-12-05 03:57

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

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

acting co

3条回答
  •  無奈伤痛
    2020-12-05 04:39

    When using AspNetCore I could not mock the ControllerContext since I got an exception.

    Unsupported expression: m => m.HttpContext
    Non-overridable members (here: ActionContext.get_HttpContext) may not be used in setup / verification expressions.

    Instead I had to mock the HttpContext and create a ControllerContext and pass the HttpContext object along.

    I did find that mocking claims or response/request objects works as well when using this method.

    [Test]
    public void TestSomeStuff() {
      var name = "some name";
    
      var httpContext = new Mock();
      httpContext.Setup(m => m.User.IsInRole("RoleName")).Returns(true);
      httpContext.Setup(m => m.User.FindFirst(ClaimTypes.Name)).Returns(name);
    
      var context = new ControllerContext(new ActionContext(httpContext.Object, new RouteData(), new ControllerActionDescriptor());
    
      var controller = new MyController()
      {
        ControllerContext = context
      };
    
      var result = controller.Index();
      Assert.That(result, Is.Not.Null);
    }
    

提交回复
热议问题