响应.StatusCode在非单元测试中为空
本文关键字:单元测试 StatusCode 响应 | 更新日期: 2023-09-27 17:50:35
我正在写单元测试用例。我正试图为这种方法编写单元测试,但显示错误。如何在mvc3框架和rhino mock中对该方法进行单元测试。
public ActionResult UnderConstruction()
{
Response.StatusCode = (int)HttpStatusCode.TemporaryRedirect;
ErrorModel model = new ErrorModel()
{
ErrorMessage = "This page is still under construction; please check back later.",
Title = "Under Construction"
};
return View("Error", model);
}
为空的是Response
,而不是Response.StatusCode
。您需要模拟HttpContextBase
和HttpResponseBase
,然后创建并分配控制器的ControllerContext
。
测试将看起来像这样(对不起,如果我伪造Rhino Mock代码;我通常使用Moq):
// arrange
var httpContext = MockRepository.GenerateMock<HttpContextBase>();
var request = MockRepository.GenerateMock<HttpRequestBase>();
var response = MockRepository.GenerateMock<HttpResponseBase>();
// stub both Request and Response, for good measure.
httpContext.Stub(x => x.Request).Return(request);
httpContext.Stub(x => x.Response).Return(response);
var controller = new YourController();
// create and assign the controller context
var context = new ControllerContext(httpContext,
new RouteData(),
controller);
controller.ControllerContext = context;
// act
var actual = controller.UnderConstruction() as ViewResultBase;
// assert
Assert.That(actual, Is.Not.Null);
Assert.That(controller.Response.StatusCode, Is.EqualTo(HttpStatusCode.TemporaryRedirect));
// etc.