【问题标题】:Mocking Querystring-RhinoMocks-MVC3模拟查询字符串-RhinoMocks-MVC3
【发布时间】:2013-03-27 18:21:06
【问题描述】:

我有一个模拟查询字符串的情况。 有没有人用 RhinoMocks 模拟 Querystring,如果有,请告诉我。我正在使用 MVC 3。

谢谢

【问题讨论】:

标签: asp.net-mvc-3


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    虽然您要求 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;
    

    【讨论】:

    • 必须有更短的方法,。
    • @ByteBlast 如果您找到更短的方法,请在此处发布。
    • 根据您的回答(谢谢)和其他一些人,我想出了这个身体略短的助手:gist.github.com/ByteBlast/8fbbb425bc60f582780e
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多