gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:27:30 26 4
gpt4 key购买 nike

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

我的问题是我使用 Moq 来模拟 Controller ,每当我运行使用此 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;
}

这将返回一个代理 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-mvc - ASP.NET MVC - 使用 Moq 框架对 RenderPartialViewToString() 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3621961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com