c# - Response.StatusCode 在 nunit 测试中为 null

标签 c# asp.net-mvc asp.net-mvc-3 nunit response

我正在编写单元测试用例。我正在尝试为此方法编写单元测试但显示错误。如何在 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 为 null,而不是 Response.StatusCode。您需要模拟 HttpContextBaseHttpResponseBase,然后创建并分配 Controller 的 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.    

关于c# - Response.StatusCode 在 nunit 测试中为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14134658/

相关文章:

c# - 无法在按钮单击 MVC、C# 上获取选定的网格行值

c# - 如何创建自定义 NHibernate 配置属性?

c# - 版本号的正则表达式

jquery - Trirand jqGrid 未显示; TypeError : $(. ..).jqGrid 不是函数

c# - MVC Razor 路由建议

asp.net-mvc - 在 MVC3 中为图像指定 src 的正确方法

c# - SharedAccessExpiryTime 的最大限制是 60 分钟吗?

c# - 如何防止 Ace 在当前目录中寻找主题和模式?

asp.net-mvc - 带有 JSON REST Web 服务的 ASP.NET MVC

c# - PreApplicationStartMethod 何时真正被触发运行?