Unit testing 什么是单元测试MVC4响应状态代码
我有一个单元测试,它测试包含太多段的路由,但我想将它扩展到测试Unit testing 什么是单元测试MVC4响应状态代码,unit-testing,asp.net-mvc-4,httpcontext,Unit Testing,Asp.net Mvc 4,Httpcontext,我有一个单元测试,它测试包含太多段的路由,但我想将它扩展到测试响应状态代码(应该返回404代码) 可以使用模拟的httpContext并检查状态代码吗 HttpContextMock.Object.Response.StatusCode始终返回0个状态代码(我想是因为只模拟了HttpContext的一部分) 和Web.Config规则 <httpErrors errorMode="Custom" existingResponse="Replace"> <remove st
响应状态代码
(应该返回404代码)
可以使用模拟的httpContext并检查状态代码吗
HttpContextMock.Object.Response.StatusCode
始终返回0个状态代码(我想是因为只模拟了HttpContext
的一部分)
和Web.Config
规则
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
</httpErrors>
下面的单元测试将验证HttpStatusCode是否设置为404。注意,它必须在控制器的操作中设置,正如您在问题中所做的那样。如果您希望Web.config进行交互,那么它更像是一个Web集成测试,这是一个完全不同的测试
[TestMethod]
公共无效路由到多个分段()
{
var httpContextStub=new Mock();
var httpResponseMock=new Mock();
var controllerContextStub=new Mock();
设置(x=>x.Response).Returns(httpResponseMock.Object);
controllerContextStub.Setup(x=>x.HttpContext)
.Returns(httpContextStub.Object);
var sut=新的错误控制器
{ControllerContext=controllerContextStub.Object};
sut.NotFound();
httpResponseMock.VerifySet(x=>x.StatusCode=404);
}
是的,我在考虑web集成测试的方向。
public class ErrorController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult NotFound()
{
Response.StatusCode = 404;
return View();
}
}
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
</httpErrors>
[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);
}