如何测试由ASP. net设置的HTTP状态码.. NET MVC操作与MSpec

本文关键字:状态 HTTP NET MVC MSpec 操作 设置 何测试 测试 net ASP | 更新日期: 2023-09-27 18:10:06

我有以下控制器:

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

我已经创建了一个MSpec规范:

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

但是由于我实例化控制器的方式,HttpContext是空的。测试由PageNotFound动作设置的状态码的最佳方法是什么?

编辑:在下面贴了一个答案

如何测试由ASP. net设置的HTTP状态码.. NET MVC操作与MSpec

找到了使用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
                         };
    };
}

不是很优雅。如果你能想到更好的方法,请告诉我。

您可以使用:

_controller.Response.StatusCode

另一个使用MvcContrib的TestControllerBuilder的选项…

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

,然后使用NUnit(我猜Moq版本会像你有它一样工作)…

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

所有丑陋的设置和模拟工作仍在完成,但由MvcContrib而不是在测试中完成。这里有一篇关于使用TestControllerBuilder的文章