我在MVC3中有一个 Controller ,如果出现问题,该 Controller 需要返回响应代码500。我通过返回一个 View 对象并将http响应代码设置为等于500来做到这一点(我已经在firebug中检查了这一点,并且一切正常。)
public ActionResult http500()
{
ControllerContext.HttpContext.Response.StatusCode = 500;
ControllerContext.HttpContext.Response.StatusDescription = "An error occurred whilst processing your request.";
return View();
}
我现在遇到的问题是,我需要能够编写一个检查响应代码的单元测试。我试图通过ViewResult对象和Controller上下文以几种不同的方式访问响应代码。
两种方法都不会给我在 Controller 中设置的响应代码。
[TestMethod()]
public void http500Test()
{
var controller = new ErrorController();
controller.ControllerContext = new ControllerContext(FakeHttpObject(), new RouteData(), controller);
ViewResult actual = controller.http500() as ViewResult;
Assert.AreEqual(controller.ControllerContext.HttpContext.Response.StatusCode, 500);
}
我将如何从 Controller 获取响应代码500,或者更多是集成测试。
最佳答案
如何以更MVCish的方式进行操作:
public ActionResult Http500()
{
return new HttpStatusCodeResult(500, "An error occurred whilst processing your request.");
}
然后:
// arrange
var sut = new HomeController();
// act
var actual = sut.Http500();
// assert
Assert.IsInstanceOfType(actual, typeof(HttpStatusCodeResult));
var httpResult = actual as HttpStatusCodeResult;
Assert.AreEqual(500, httpResult.StatusCode);
Assert.AreEqual("An error occurred whilst processing your request.", httpResult.StatusDescription);
或者,如果您坚持使用Response对象,则可以创建一个伪造的对象:
// arrange
var sut = new HomeController();
var request = new HttpRequest("", "http://example.com/", "");
var response = new HttpResponse(TextWriter.Null);
var httpContext = new HttpContextWrapper(new HttpContext(request, response));
sut.ControllerContext = new ControllerContext(httpContext, new RouteData(), sut);
// act
var actual = sut.Http500();
// assert
Assert.AreEqual(500, response.StatusCode);
Assert.AreEqual("An error occurred whilst processing your request.", response.StatusDescription);
关于asp.net-mvc-3 - MVC3单元测试响应代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9871700/