我是 MOQ 的新手,但我将它与 NUnit 一起用于单元测试。
我已经模拟了我的控制器的所有部分,除了以下行,它会引发“对象未设置为对象的实例”错误消息。
Response.Cookies.Clear();
我有以下扩展方法来模拟控制器上下文,它适用于我迄今为止遇到的所有其他事情(非常感谢这个论坛上的好人)。
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 Clear() method
//
// Mock the controller context (using the objects mocked above)
//
var moqCtx = new Mock<ControllerContext>(context.Object, new RouteData(), ctl);
moqCtx.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(username);
moqCtx.SetupGet(p => p.HttpContext.User.Identity.IsAuthenticated).Returns(true);
if (!string.IsNullOrEmpty(role.ToString()))
moqCtx.Setup(p => p.HttpContext.User.IsInRole(role.ToString())).Returns(true);
//
// Pass the mocked ControllerContext and create UrlHelper for the controller and return
//
ctl.ControllerContext = moqCtx.Object;
ctl.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);
return 1;
}
正如您在上面看到的,我试图模拟 cookie 集合的“获取”,但这没有帮助。
此外,不能模拟实际的 Clear() 方法,因为它不是虚拟方法。
显然我不想测试 cookie 是否被清除,我只想能够在测试中忽略它。
谢谢,
格雷格