0

I'm tyring to use Moq to determine if a user has a certain role. I tried the following example in the default MVC project (How to mock Controller.User using moq), however I'm getting the following error when running the test.

Expected invocation on the mock at least once, but was never performed: p => p.IsInRole("admin")

 [TestMethod] public void HomeControllerReturnsIndexViewWhenUserIsAdmin() { var homeController = new HomeController(); var userMock = new Mock<IPrincipal>(); userMock.Setup(p => p.IsInRole("admin")).Returns(true); var contextMock = new Mock<HttpContextBase>(); contextMock.SetupGet(ctx => ctx.User) .Returns(userMock.Object); var controllerContextMock = new Mock<ControllerContext>(); controllerContextMock.SetupGet(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"); } 

It sure looks like IsInRole("admin") is being called, so I'm not sure why I'm getting this error.

5
  • I'm not familiar with Moq's internals, but how Moq determines String equality may be an issue. Try declaring final String ADMIN = "admin"; and then use p.IsInRole(ADMIN) to see if that makes a difference. Commented Dec 2, 2013 at 17:51
  • 3
    Does the controller code explicitly calls IsInRole("admin") or is it just a filter attribute? (If it is the later then you may just want to check that the attribute exists) Commented Dec 2, 2013 at 20:37
  • Are you able to update your question with the method under test ? Usually you get this error when the method has not been called correctly or the setup is not configured correctly. Commented Dec 2, 2013 at 21:31
  • @WhiskerBiscuit Do you still have the same issue? Commented Dec 3, 2013 at 10:59
  • @Daniel J.G. is right. It is possible to mock homeController.ControllerContext.User.IsInRole("admin") if it is called within the Index() method. Commented Dec 3, 2013 at 15:57

1 Answer 1

1

You're never calling

userMock.Object.IsInRole("admin") 

You are setting it up such that

userMock.Object.IsInRole("admin") == true 

and you are trying to verify that it was called in such a way, but the call to Verify fails as you never called IsInRole("admin") manually and neither did the Index method of the HomeController.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.