模拟查询字符串-Rhino Mocks-MVC3

时间:2011-08-17 15:18:14

标签: asp.net-mvc-3

我有Mock Querystring的情况。 有没有人用RhinoMocks嘲笑Querystring,如果有的话请告诉我。我正在使用MVC 3。

谢谢

2 个答案:

答案 0 :(得分:4)

我找到了基于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;

答案 1 :(得分:1)

虽然您要求使用RhinoMocks,但我找到了这个解决方案并将其改编为Moq。所以对于其他感兴趣的人来说,这里是@ TomAx的答案的Moq版本:

        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;