【问题标题】:How to test HTTP status code set by an ASP.NET MVC action with MSpec如何使用 MSpec 测试由 ASP.NET MVC 操作设置的 HTTP 状态代码
【发布时间】:2011-11-27 15:03:00
【问题描述】:

我有以下控制器:

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 操作设置的状态代码的最佳方法是什么?

编辑:在下面发布答案

【问题讨论】:

    标签: c# asp.net-mvc-3 unit-testing moq mspec


    【解决方案1】:

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

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

    然后使用 NUnit(我猜 Moq 版本会像你拥有的那样工作)...

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

    所有丑陋的设置和模拟工作仍在完成,但由 MvcContrib 而不是在测试内部完成。这是using the TestControllerBuilder上的帖子。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        你可以使用:

        _controller.Response.StatusCode
        

        【讨论】:

        猜你喜欢
        • 2012-08-20
        • 2013-12-06
        • 1970-01-01
        • 2012-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多