Search code examples
c#unit-testingasp.net-mvc-4securitymicrosoft-fakes

Unit testing WebMatrix.WebData with Microsoft Fake Framework MVC4


I can't test any logoff, login, register action from AccountController with the new Microsoft Fake Framework without having this error message: System.Security.VerificationException: Operation could destabilize the runtime.

The unit test is real simple:

    [TestMethod]
    public void LogOff()
    {
        var AccountController = new AccountController();
        RedirectToRouteResult RedirectToRouteResult;

        //Scope the detours we're creating
        using (ShimsContext.Create())
        {
            ShimWebSecurity.Logout = () => {  };
            var test = AccountController.LogOff();
            RedirectToRouteResult = AccountController.LogOff() as RedirectToRouteResult;
        }

        Assert.IsNotNull(RedirectToRouteResult);
        Assert.AreEqual("Index", RedirectToRouteResult.RouteValues["Action"]);
        Assert.AreEqual("Home", RedirectToRouteResult.RouteValues["controller"]);
    }

Also find this: http://social.msdn.microsoft.com/Forums/en-US/vsunittest/thread/f84962ea-a9b2-4e0d-873b-e3cf8cfb37e2 that talk about the same bug but no answer.

Thanks!


Solution

  • I asked the same question before VS2012 Update 1 was released (VerificationException when instantiating MVC controller during unit testing) and I got the response from a guy from Microsoft who said that they are working on it and it should be available in the next update. Well, nothing since then.

    However, in order to get the result and to continue testing using Microsoft Fakes Framework, I wrapped the calls to MVC methods like those in the UrlHelper class with my own private methods that return primitive types like string and then Shim the unit test to give me a desired result. That way I never made a call to the underlying MVC infrastructure and I got the desired result. Also, you will need to remove System.Web.Mvc.Fakes reference otherwise VerificationException will keep popping up.

    If you find this tedious then you should switch to a more mature unit testing framework like Moq or Rhino.