【发布时间】:2013-03-27 18:21:06
【问题描述】:
我有一个模拟查询字符串的情况。 有没有人用 RhinoMocks 模拟 Querystring,如果有,请告诉我。我正在使用 MVC 3。
谢谢
【问题讨论】:
-
取决于您在控制器中处理查询字符串的方式。你会发布你的控制器吗?
标签: asp.net-mvc-3
我有一个模拟查询字符串的情况。 有没有人用 RhinoMocks 模拟 Querystring,如果有,请告诉我。我正在使用 MVC 3。
谢谢
【问题讨论】:
标签: asp.net-mvc-3
我找到了一个基于 http://dylanbeattie.blogspot.com/2008/12/mocking-querystring-collection-in.html 但使用 RhinoMocks 的解决方案
HttpContextBase httpContextBase;
HttpRequestBase httpRequestBase;
ControllerBase controllerBase;
controllerBase = mockRepository.DynamicMock<ControllerBase>();
NameValueCollection nvc = new NameValueCollection();
nvc.Add("KEY", "VALUE");
httpRequestBase = mockRepository.DynamicMock<HttpRequestBase>();
Expect.Call(httpRequestBase.QueryString).Return(nvc);
httpContextBase = mockRepository.DynamicMock<HttpContextBase>();
Expect.Call(httpContextBase.Request).Return(httpRequestBase);
var context = new ControllerContext(httpContextBase, new RouteData(), controllerBase);
yourController.ControllerContext = context;
【讨论】:
虽然您要求 RhinoMocks,但我找到了这个解决方案并将其调整为 Moq。因此,对于其他感兴趣的人,这是@TomAx 答案的起订量版本:
NameValueCollection queryString = new NameValueCollection();
queryString.Add("KEY", "VALUE");
// Set up a request
var request = new Mock<HttpRequestBase>();
request.Setup(r => r.QueryString).Returns(queryString);
// Inject into the controller
var controllerBase = new Mock<ControllerBase>();
var contextBase = new Mock<HttpContextBase>();
contextBase.Setup(c => c.Request).Returns(request.Object);
request.Setup(r => r.QueryString).Returns(queryString);
var controllerContext = new ControllerContext(contextBase.Object, new RouteData(), controllerBase.Object);
var controller = new YourController();
controller.ControllerContext = controllerContext;
【讨论】: