MVC3单元测试响应code [英] MVC3 unit testing response code

查看:106
本文介绍了MVC3单元测试响应code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MVC3控制器,它需要,如果出现错误返回响应code 500。我通过返回一个视图对象并设置HTTP响应code等于500这样做(我已经在Firebug检查这和所有工作很大)。

I have a controller within MVC3 which needs to return a response code 500 if something goes wrong. I am doing this by returning a view object and setting http response code to equal 500 (I have checked this in firebug and all is working great).

public ActionResult http500()
{
    ControllerContext.HttpContext.Response.StatusCode = 500;
    ControllerContext.HttpContext.Response.StatusDescription = "An error occurred whilst processing your request.";

    return View();
}

我现在的问题是我需要能够写一个单元测试,检查响应code。我曾尝试访问响应code在两者通过的ViewResult对象和控制器上下文几种不同的方式。

The problem I have now is I need to be able to write a unit test which checks the response code. I have tried accessing the response code in several different ways both through the ViewResult object and the Controller context.

办法都没有给我回应code我已经在控制器设置。

Neither way gives me the response code I have set in the 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);

}

我怎么会去从控制器得到响应code 500或这更的集成测试的事情。

How would I go about getting the response code 500 from the controller or is this more of an integration testing thing.

推荐答案

如何更MVCish的方式做:

How about doing it in a more MVCish way:

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对象可以创建一个假的:

or if you insist on using the Response object you could create a fake one:

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

这篇关于MVC3单元测试响应code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆