ASP.NET MVC - 使用Moq框架对RenderPartialViewToString()进行单元测试?

时间:2010-09-01 20:35:02

标签: asp.net-mvc unit-testing asp.net-mvc-2 moq

我正在使用这个辅助方法将我的PartialViewResult转换为字符串并将其作为Json返回 - http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/

我的问题是我使用Moq来模拟控制器,每当我运行使用这个RenderPartialViewToString()方法的单元测试时,我得到了“对象引用未设置为对象的实例”。 ControllerContext上的错误。

private ProgramsController GetController()
{
var mockHttpContext = new Mock<ControllerContext>();
mockHttpContext.SetupGet(p => p.HttpContext.User.Identity.Name).Returns("test");
mockHttpContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);
// Mock Repositories
var mockOrganizationRepository = new MockOrganizationRepository(MockData.MockOrganizationsData());
var mockIRenderPartial = new BaseController();
var controller = new ProgramsController(mockOrganizationRepository, mockIRenderPartial);
controller.ControllerContext = mockHttpContext.Object;
return controller;
}

这会返回一个代理控制器,也许这就是我收到错误的原因。知道如何对此进行单元测试吗?

非常感谢。

1 个答案:

答案 0 :(得分:4)

试试这个:

public static void SetContext(this Controller controller)
        {
            var httpContextBase = new Mock<HttpContextBase>();
            var httpRequestBase = new Mock<HttpRequestBase>();
            var respone = new Mock<HttpResponseBase>();
            var session = new Mock<HttpSessionStateBase>();
            var routes = new RouteCollection();
            RouteConfigurator.RegisterRoutesTo(routes);

            httpContextBase.Setup(x => x.Response).Returns(respone.Object);
            httpContextBase.Setup(x => x.Request).Returns(httpRequestBase.Object);
            httpContextBase.Setup(x => x.Session).Returns(session.Object);
            session.Setup(x => x["somesessionkey"]).Returns("value");
            httpRequestBase.Setup(x => x.Form).Returns(new NameValueCollection());
            controller.ControllerContext = new ControllerContext(httpContextBase.Object, new RouteData(), controller);
            controller.Url = new UrlHelper(new RequestContext(controller.HttpContext, new RouteData()), routes);
        }