我有一个测试路径包含太多段的单元测试,但我想将其扩展到测试Response Status Code
(应返回404代码)。
是否可以使用该模拟的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 :(得分: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);
}