Setting Response.StatusCode using MvcContrib.TestHelpher

180 views Asked by At

I've got a very simple test method, using MvcContrib.TestBuilder to setup the controller (and mock the HttpContext etc...)

    [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));
    }

My implementation looks as simple as:

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

        return View();
    }

However, my test is always failing, because Response.StatusCode is always 0

Even if I debug, and evaluate Response.StatusCode after Response.StatusCode = 404; it is still 0

1

There are 1 answers

0
Darin Dimitrov On BEST ANSWER

The HttpResponse instance is a mock. So you should assert it like this:

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

instead of:

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

But instead of setting some status codes in my controller action I would simply return the proper ActionResult:

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

and test it like this:

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

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

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

Looks more readable IMHO.