使用模拟框架(Moq)进行MVC测试

时间:2010-07-05 07:04:00

标签: asp.net-mvc unit-testing asp.net-mvc-2 moq

我正在使用Moq帮助测试我的ASP.NET MVC2应用程序。

问题:用户代码未处理ArgumentException。无法获取StrongNameKeyPair的公钥

此代码改编自Scott Hanselman的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");
    }

在WinXP下使用Moq引用... VS2010。

1 个答案:

答案 0 :(得分:1)

您的代码没有任何问题。我刚刚测试过,它工作正常。问题在于Moq程序集。您需要向C:\Documents and Settings\AllUsers\ApplicationData\Microsoft\Crypto\RSA\MachineKeys文件夹授予特定权限。结帐this discussion

右键单击Windows资源管理器中的Moq.dll,然后在属性中确保它未锁定。当您从Internet下载某些DLL时,Windows会自动对其应用受限制的权限。