Given: I needed to unit test that a response status code had been set within a controller action.
When: I didn't particularly want to refactor due to this being existing code.
Then: After experimenting unsuccessfully with creating various HttpContext classes, I found the simplest solution to be as follows within my test method:
var request = new HttpRequest("", "http://tempuri.org/", "");
var response = new HttpResponse(TextWriter.Null);
var httpContext = new HttpContextWrapper(new HttpContext(request, response));
_myController.ControllerContext = new ControllerContext(httpContext, new RouteData(), _myController);
var result = _myController.SomeAction(...some parameters...);
Assert.AreEqual(400, response.StatusCode);
Monday, 30 April 2018
Subscribe to:
Posts (Atom)