views:

67

answers:

2

Hi

I'm using Moq to help in testing my ASP.NET MVC2 application.

Problem: ArgumentException was unhandled by user code. Unable to obtain public key for StrongNameKeyPair

This code has been adapted from Scott Hanselman's NerdDinner1.

HomeController CreateHomeControllerAs(string userName)
    {
        var mock = new Mock<ControllerContext>();
        mock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName); // fails here
        mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);

        var controller = new HomeController();
        controller.ControllerContext = mock.Object;

        return controller;
    }

    [TestMethod]
    public void should_be_able_to_get_to_index_page_logged_in()
    {
        HomeController controller = CreateHomeControllerAs("dave");
    }

Using Moq referenced... VS2010 under WinXP.

A: 

You need to mock HttpContextBase. See this answer

http://stackoverflow.com/questions/677801/mocking-and-httpcontextbase-get-user

Daz Lewis
+1  A: 

There's nothing wrong with your code. I've just tested it and it worked fine. The problem is with the Moq assembly. You need to grant specific permissions to the C:\Documents and Settings\AllUsers\ApplicationData\Microsoft\Crypto\RSA\MachineKeys folder. Checkout this discussion.

Also right click on the Moq.dll in Windows Explorer and in the properties make sure that it is not locked. When you download some DLL from the internet Windows automatically applies restricted permissions to it.

Darin Dimitrov
Awesome.. I wrote a blog post on this too http://www.programgood.net/2010/07/05/ArgumentExceptionWasUnhandledByUserCodeUnableToObtainPublicKeyForStrongNameKeyPair.aspx
Dave