问题
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