edi*_*ode 1 c# unit-testing asp.net-mvc-4
我写了一个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);
}
Run Code Online (Sandbox Code Playgroud)
GetViewModel 除了在视图模型上设置属性之外什么也不做
测试
[SetUp]
public void Setup()
{
this.httpContext = new Mock<HttpContextBase>();
this.httpResponse = new Mock<HttpResponseBase>();
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<ControllerContext>(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);
}
Run Code Online (Sandbox Code Playgroud)
我在哪里错了?
只需在设置阶段添加:
httpResponse.SetupAllProperties();
Run Code Online (Sandbox Code Playgroud)
话虽这么说,你可能不需要这两个断言:
this.httpResponse.VerifySet(x => x.StatusCode = (int)HttpStatusCode.NotFound);
Assert.AreEqual((int)HttpStatusCode.NotFound, this.httpResponse.StatusCode);
Run Code Online (Sandbox Code Playgroud)
第一个应该足以进行单元测试.
| 归档时间: |
|
| 查看次数: |
3070 次 |
| 最近记录: |