asp.net mvc rhino mocks mocking httprequest values

核能气质少年 提交于 2019-12-24 03:38:12

问题


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);
  }

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


回答1:


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 );

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();


来源:https://stackoverflow.com/questions/3195839/asp-net-mvc-rhino-mocks-mocking-httprequest-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!