Hi,
How do I go about creating a mock request for my asp.net-mvc application for unit-testing?
What options do I have?
I am using FormsCollection in my Actions so I can simulate form input data also.
Hi,
How do I go about creating a mock request for my asp.net-mvc application for unit-testing?
What options do I have?
I am using FormsCollection in my Actions so I can simulate form input data also.
Hi,
You just have to create a new instance of FormCollection and add the data inside of it.
So you can call something like this without mocking anything.
var result = controller.Create(new FormCollection { { "InvoiceId", "-1" } }) as RedirectToRouteResult;
Otherwise if your code calls something like Request or HttpContext you can use the following extension method (inspired from the Scott Hanselman's one)
I am using RhinoMocks.
public static HttpContextBase SetHttpContext(this MockRepository mocks, Controller controller, HttpCookieCollection cookies) {
cookies = cookies ?? new HttpCookieCollection();
var request = mocks.StrictMock<HttpRequestBase>();
var context = mocks.StrictMock<HttpContextBase>();
var response = mocks.StrictMock<HttpResponseBase>();
SetupResult.For(context.Request).Return(request);
SetupResult.For(context.Response).Return(response);
SetupResult.For(request.Cookies).Return(cookies);
SetupResult.For(request.IsSecureConnection).Return(false);
SetupResult.For(response.Cookies).Return(cookies);
if (controller != null)
{
controller.ControllerContext = new ControllerContext(context, new RouteData(), controller);
}
if (!string.IsNullOrEmpty(requestUrl))
{
request.SetupRequestUrl(requestUrl);
SetupResult.For(response.ApplyAppPathModifier(null)).IgnoreArguments().Return(null);
}
return context;
}