ASP.NET MVC - 单元测试RenderPartialViewToString()与起订量的框架? [英] ASP.NET MVC - Unit testing RenderPartialViewToString() with Moq framework?

查看:83
本文介绍了ASP.NET MVC - 单元测试RenderPartialViewToString()与起订量的框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个helper方法把我的PartialViewResult成字符串并将其返回为JSON - <一个href=\"http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/\">http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/

I'm using this helper method to turn my PartialViewResult into string and returning it as Json - http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/

我的问题是,我使用起订量来模拟控制器,每当我运行单元测试使用这个RenderPartialViewToString()方法中,我得到了对象引用不设置到对象的实例。错误的ControllerContext。

My problem is that I'm using Moq to mock the controller, and whenever I run unit test that uses this RenderPartialViewToString() method, I got the "Object reference not set to an instance of an object." error on 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;
}

这会返回一个代理控制器,也许这就是为什么我得到这个错误的原因。任何想法如何单元测试呢?

This returns a proxy controller, and maybe it's the reason why I got that error. Any idea how to unit testing this?

非常感谢你。

推荐答案

试试这个:

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 MVC - 单元测试RenderPartialViewToString()与起订量的框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆