小编Gre*_*reg的帖子

MOQ - 模拟MVC控制器的Response.Cookies.Clear()

我是MOQ的新手,但我正在使用NUnit进行单元测试.

我已经模拟了我的控制器的所有部分,除了以下行抛出"对象未设置为对象的实例"错误消息.

Response.Cookies.Clear();
Run Code Online (Sandbox Code Playgroud)

我有以下扩展方法来模拟控制器上下文,该上下文适用于我迄今为止遇到的所有其他内容(非常感谢此论坛上的优秀人员).

public static int SetUpForTest(this System.Web.Mvc.Controller ctl, string username, TestingUtility.Roles role)
    {
        var routes = new RouteCollection();
        MvcApplication.RegisterRoutes(routes);

        var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
        request.SetupGet(x => x.ApplicationPath).Returns("/");
        request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/a", UriKind.Absolute));
        request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());

        var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
        response.Setup(x => x.ApplyAppPathModifier(Moq.It.IsAny<String>())).Returns((String url) => url);
        // response.SetupGet(x => x.Cookies).Returns(new HttpCookieCollection()); // This also failed to work

        var context = new Mock<HttpContextBase>(MockBehavior.Strict);
        context.SetupGet(x => x.Request).Returns(request.Object);
        context.SetupGet(x => x.Response).Returns(response.Object);
        context.SetupGet(x => x.Response.Cookies).Returns(new HttpCookieCollection()); // still can't call the …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc nunit moq

10
推荐指数
1
解决办法
7406
查看次数

标签 统计

asp.net-mvc ×1

c# ×1

moq ×1

nunit ×1