asp.net mvc犀牛模拟嘲笑httprequest值 [英] asp.net mvc rhino mocks mocking httprequest values

查看:91
本文介绍了asp.net mvc犀牛模拟嘲笑httprequest值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写测试,我可以模拟HttpRequestBase来返回这样的帖子值吗?我怎样才能做到这一点?

I'm trying to write a test can I mock a HttpRequestBase to return post values like this? How can I achieve this?

var collection = new NameValueCollection();
collection.Add("Id", "1");
collection.Add("UserName", "");


var mocks = new MockRepository();

  using (mocks.Record())
  {
      Expect.Call(requestBase.Params).Return(collection);
  }

基本上,我有一个要求,要求我模拟请求发布参数而不是表单值,因为UI客户端不是html表单,是否有任何想法如何伪造/模拟httprequest发布参数?返回类型是nameVaueCollection

Basically I have a requirement that rquires me to mock request post parameters as opposed to form values as the UI client is not a html form, any ideas how to fake/mock the httprequest post params? the return type is a nameVaueCollection

推荐答案

您不会喜欢听到此消息,但是您将以错误的方式进行此操作.您应该使用模型作为输入,并让模型绑定器填充属性,而不是直接从请求参数中获取值.这将使您的生活(包括模拟)变得更加容易,因为您将提供模型作为操作方法的参数,而不必模拟HttpRequest对象.

You're not going to like hearing this, but you're going about this the wrong way. You should be using models for your inputs and letting the model binder fill in the properties rather than getting the values out of the request parameters directly. This will make your life, including mocking much easier, since you'll be supplying a model as a parameter to the action method rather than having to mock up the HttpRequest object.

var model = new UserModel { ID = 1, UserName = string.Empty };

var controller = new FooController();

var result = controller.FooAction( model );

如果必须使用参数,那么至少我建议您对模拟使用AAA语法.

If you must use the parameters, then at least I suggest you use the AAA syntax for your mocks.

var request = MockRepository.GenerateMock<HttpRequestBase>();
var context = MockRepository.GenerateMock<HttpContextBase>();

var collection = new NameValueCollection();   
collection.Add("Id", "1");   
collection.Add("UserName", "");

context.Expect( c => c.Request ).Return( request ).Repeat.Any();
request.Expect( r => r.Params ).Return( collection ).Repeat.Any()

var controller = new FooController();
controller.ControllerContext = new ControllerContext( context, new RouteData(), controller );

var result = controller.FooAction();

...

context.VerifyAllExpectations();
request.VerifyAllExpectations();

这篇关于asp.net mvc犀牛模拟嘲笑httprequest值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆