How to check HTTP status code set by ASP.NET MVC action using MSpec

I have the following controller:

public sealed class SomeController : Controller
{
    public ActionResult PageNotFound()
    {
        Response.StatusCode = 404;

        return View("404");
    }
}

I created the MSpec specification:

[Subject(typeof (SomeController))]
public class when_invalid_page_is_requested : SomeControllerSpec
{
    Because of = () => result = Controller.PageNotFound();

    It should_set_status_code_to_404 = 
        () => Controller.Response.StatusCode.ShouldEqual(404);
}

public abstract class SomeControllerSpec
{
    protected static HomeController Controller;

    Establish context = () => { Controller = new SomeController(); };
}

But due to the way I create the controller instance, the HttpContext is null. What would be the best way to check the status code set by the action PageNotFound?

EDIT: answer below

+5
source share
3 answers

Found a way to do this with Moq.

[Subject(typeof (SomeController))]
public class when_invalid_page_is_requested : SomeControllerSpec
{
    Because of = () => result = Controller.PageNotFound();

    It should_set_status_code_to_404 = 
        () => HttpResponse.VerifySet(hr => hr.StatusCode = 404);
}

public abstract class SomeControllerSpec
{
    protected static SomeController Controller;
    protected static Mock<ControllerContext> ControllerContext;
    protected static Mock<HttpResponseBase> HttpResponse;

    Establish context = () =>
    {
        ControllerContext = new Mock<ControllerContext>();
        HttpResponse = new Mock<HttpResponseBase>();
        ControllerContext.SetupGet(cc => cc.HttpContext.Response)
                         .Returns(HttpResponse.Object);

        Controller = new SomeController
                         {
                             ControllerContext = ControllerContext.Object
                         };
    };
}

Not very elegant. If you can come up with a better way, let me know.

+6
source

You can use:

_controller.Response.StatusCode
+3
source

, MvcContrib TestControllerBuilder...

var myController = new MyController();

var testControllerBuilder = new TestControllerBuilder();
testControllerBuilder.InitializeController(myController);

NUnit ( , Moq , )...

myController.Response.AssertWasCalled( response => response.StatusCode = 400 );

All the ugly tweaks and bullying work is still in progress, but MvcContrib is instead a test. Here's a post using TestControllerBuilder .

+3
source

All Articles