我写了一个ErrorsController
你可以想象的,有一些非常简单的方法可以在错误的情况下继续提供动态内容,例如500.
现在我要做的是测试在该方法中,HttpResponseBase.StatusCode
在执行此方法时将其设置为给定数字,但由于某种原因,该StatusCode
属性始终为0.这包括在设置后直接检查属性时.
调节器
public ViewResult NotFound() { Response.StatusCode = (int)HttpStatusCode.NotFound; const string PageTitle = "404 Page Not Found"; var viewModel = this.GetViewModel(PageTitle); return this.View(viewModel); }
GetViewModel
除了在视图模型上设置属性之外什么也不做
测试
[SetUp] public void Setup() { this.httpContext = new Mock(); this.httpResponse = new Mock (); this.httpContext.SetupGet(x => x.Response).Returns(this.httpResponse.Object); this.requestContext = new RequestContext(this.httpContext.Object, new RouteData()); this.controller = new ErrorsController(this.contentRepository.Object); this.controllerContext = new Mock (this.requestContext, this.controller); this.controllerContext.SetupGet(x => x.HttpContext.Response).Returns(this.httpResponse.Object); this.controller.ControllerContext = this.controllerContext.Object; } [Test] public void Should_ReturnCorrectStatusCode_ForNotFoundAction() { this.controller.NotFound(); this.httpResponse.VerifySet(x => x.StatusCode = (int)HttpStatusCode.NotFound); Assert.AreEqual((int)HttpStatusCode.NotFound, this.httpResponse.StatusCode); }
我在哪里错了?
只需在设置阶段添加:
httpResponse.SetupAllProperties();
话虽这么说,你可能不需要这两个断言:
this.httpResponse.VerifySet(x => x.StatusCode = (int)HttpStatusCode.NotFound); Assert.AreEqual((int)HttpStatusCode.NotFound, this.httpResponse.StatusCode);
第一个应该足以进行单元测试.