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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – ASP.NET MVC – 使用Moq框架对RenderPartialViewToString()进行单元测试?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用这个帮助方法将我的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;
}

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

非常感谢你.

解决方法

尝试这个:
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);
        }

猜你在找的asp.Net相关文章