1

我有一个非常简单的测试方法,使用 MvcContrib.TestBuilder 来设置控制器(并模拟 HttpContext 等......)

    [Test]
    public void http404_returns_status_code_of_404()
    {
        var builder = new TestControllerBuilder();
        controller = new ErrorController();

        builder.InitializeController(controller);

        var result = controller.Http404();

        Assert.That(controller.Response.StatusCode, Is.EqualTo(404));
    }

我的实现看起来很简单:

    public ActionResult Http404()
    {
        Response.StatusCode = 404;

        return View();
    }

但是,我的测试总是失败,因为Response.StatusCode总是 0

即使我调试,然后评估Response.StatusCodeResponse.StatusCode = 404; 仍然是 0

4

1 回答 1

2

HttpResponse 实例是一个模拟。所以你应该像这样断言它:

controller.Response.AssertWasCalled(x => x.StatusCode = 404);

代替:

Assert.That(controller.Response.StatusCode, Is.EqualTo(404));

但是,我不会在我的控制器操作中设置一些状态代码,而是简单地返回正确的ActionResult

public ActionResult Http404()
{
    return new HttpNotFoundResult();
}

并像这样测试它:

// arrange
var builder = new TestControllerBuilder();
var sut = new ErrorController();
builder.InitializeController(sut);

// act
var actual = controller.Http404();

// assert
actual.AssertResultIs<HttpNotFoundResult>();

恕我直言,看起来更具可读性。

于 2013-07-26T15:07:29.973 回答