2013-12-14 79 views
1

我有一個單元測試,測試的路由段數太多,但我想擴展它來測試Response Status Code(應該返回404代碼)。單元測試MVC4響應狀態代碼

是否有可能使用模擬的httpContext並檢查狀態碼?

HttpContextMock.Object.Response.StatusCode返回0(由於嘲笑我想的HttpContext的一部分)。

[TestMethod] 
     public void RouteWithTooManySegments() 
     { 
      var routes = new RouteCollection(); 
      MyApp.RouteConfig.RegisterRoutes(routes); 

      var httpContextMock = new Mock<HttpContextBase>(); 
      var httpResponseMock = new Mock<HttpResponseBase>(); 

      httpContextMock.Setup(c => c.Request.AppRelativeCurrentExecutionFilePath) 
       .Returns("~/dawd/dawdaw/dawdaw/daw"); 

      RouteData routeData = routes.GetRouteData(httpContextMock.Object); 

      Assert.IsNull(routeData); 
     } 

使用ErrorController返回 「404」 的觀點和適當Response Status Code

public class ErrorController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public ActionResult NotFound() 
    { 
     Response.StatusCode = 404; 
     return View(); 
    } 
} 

Web.Config規則

<httpErrors errorMode="Custom" existingResponse="Replace"> 
    <remove statusCode="404" /> 
    <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" /> 
</httpErrors> 

回答

0

下面的單元測試將驗證HttpStatusCode將設置爲404 請注意,它必須在您的問題中設置在Controller的Action中。如果您期望Web.config進行交互,那麼它更像是Web集成測試,這完全是一種不同的測試。

[TestMethod] 
public void RouteWithTooManySegments() 
{ 
    var httpContextStub = new Mock<HttpContextBase>(); 
    var httpResponseMock = new Mock<HttpResponseBase>(); 
    var controllerContextStub = new Mock<ControllerContext>(); 

    httpContextStub.Setup(x => x.Response).Returns(httpResponseMock.Object); 
    controllerContextStub.Setup(x => x.HttpContext) 
     .Returns(httpContextStub.Object); 

    var sut = new ErrorController 
     { ControllerContext = controllerContextStub.Object }; 

    sut.NotFound(); 

    httpResponseMock.VerifySet(x => x.StatusCode = 404); 
} 
+0

是的我正在考慮更多的Web集成測試的方向。 – netdis