Tom Riley
Tom Riley

Reputation: 1722

Unit testing HttpStatusCode in MVC4 'System.NullReferenceException'

I am trying to unit test HttpStatusCodes in MVC4 but I keep getting a 'System.NullReferenceException' when the controller tries to set the status code on Response, which makes sense as the action is getting called directly. I cant for the life of me work out how to do it without it becoming an integration test. Somebody must have done this, any ideas? See my existing code below.

Controller

public ActionResult Index()
{
    Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
    Response.Headers.Add("Retry-After", "120");

    return View();
}

Test

[Test]
public void IndexActionShouldReturn503StatusCode()
{
    //Given
    var controller = new HomeController();

    //When
    var result = controller.Index() as HttpStatusCodeResult;

    //Then
    result.StatusCode.Should().Be((int)HttpStatusCode.ServiceUnavailable);
}

Note The requirement is for a friendly 'site down' page so I need to return both a view and the status code.

Upvotes: 0

Views: 1080

Answers (1)

Steven V
Steven V

Reputation: 16595

You're returning a ViewResult, then trying to cast it as a HttpStatusCodeResult in your unit test. Try returning a HttpStatusCodeResult instead of a view.

public ActionResult Index()
{
    Response.Headers.Add("Retry-After", "120");
    return new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable);
}

Upvotes: 2

Related Questions