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.

Community
  • 1
  • 1
WhiskerBiscuit
  • 4,795
  • 8
  • 62
  • 100
  • I'm not familiar with Moq's internals, but how Moq determines [String equality](http://stackoverflow.com/questions/767372/java-string-equals-versus) may be an issue. Try declaring `final String ADMIN = "admin";` and then use `p.IsInRole(ADMIN)` to see if that makes a difference. – eebbesen Dec 02 '13 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](http://stackoverflow.com/questions/669175/unit-testing-asp-net-mvc-authorize-attribute-to-verify-redirect-to-login-page)) – Daniel J.G. Dec 02 '13 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. – Spock Dec 02 '13 at 21:31
  • @WhiskerBiscuit Do you still have the same issue? – Spock Dec 03 '13 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. – Ilya Palkin Dec 03 '13 at 15:57

1 Answers1

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.

joelmdev
  • 11,083
  • 10
  • 65
  • 89