4

我正在编写单元测试用例。我正在尝试为此方法编写单元测试,但显示错误。如何在 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);
    }
4

1 回答 1

5

Response是空的,不是Response.StatusCode。您需要模拟HttpContextBaseand 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.    
于 2013-01-03T07:36:47.537 回答