How to mock Controller.User using moq

后端 未结 3 1418
陌清茗
陌清茗 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:35

    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();
            userMock.Expect(p => p.IsInRole("admin")).Returns(true);
    
            var contextMock = new Mock();
            contextMock.ExpectGet(ctx => ctx.User)
                       .Returns(userMock.Object);
    
            var controllerContextMock = new Mock();
            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");
        }
    

    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.

提交回复
热议问题