gpt4 book ai didi

c# - 测试函数 "System.Web.Mvc.ViewEngines.Engines.FindPartialView"

转载 作者:太空狗 更新时间:2023-10-29 19:47:23 27 4
gpt4 key购买 nike

我想(单元)测试函数 System.Web.Mvc.ViewEngines.Engines.FindPartialView 并检查 HTML 代码是否正确返回。

但是每次我开始单元测试时,它都会抛出一个“Object reference not set to an instance of an object”异常。

我已尝试通过 .net 框架源代码进行调试,但调试器变得迷失方向并随机跳转/中断而没有任何消息。

现在我想知道我在 FakeControllerContext 中遗漏了什么元素以及如何修复它。

这是我的代码:

public static string RenderPartialViewToString(string viewName, object model, ControllerContext controller)
{
if (string.IsNullOrEmpty(viewName))
viewName = controller.RouteData.GetRequiredString("action");

controller.Controller.ViewData.Model = model;

using (var sw = new StringWriter())
{
//"Error: ***.Shop.UnitTests.RenderStuffTest.RenderPartialViewToStringTest-Test method threw an exception: System.NullReferenceException – Object reference not set to an instance of an object"
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller, viewName);
controller.Controller.ViewData.Model = model;
controller.Controller.ViewBag.Part = true;

var viewContext = new ViewContext(controller, viewResult.View, controller.Controller.ViewData,
controller.Controller.TempData, sw);
viewResult.View.Render(viewContext, sw);

return sw.GetStringBuilder().ToString();
}
}

这是我的测试:

    [TestMethod]
public void RenderPartialViewToStringTest()
{
const string viewName = "_navi";
var customersController = new ArticleController();
customersController.ControllerContext = new FakeControllerContext(customersController) { RouteData =
{
Route =
new Route(
"{language}/{controller}/{action}/{id}",
new MvcRouteHandler())
,
RouteHandler = new MvcRouteHandler()
},
};

customersController.ControllerContext.RouteData.Values.Add("language", "German");
customersController.ControllerContext.RouteData.Values.Add("controller", "Article");
customersController.ControllerContext.RouteData.Values.Add("action", "Index");
customersController.ControllerContext.RouteData.Values.Add("id", "");
var model = (...);
string actual = RenderStuff.RenderPartialViewToString(viewName, model, customersController.ControllerContext);
(...)
}

对于模拟,我使用了 Rhino.Mocks 和来自 Stephenwalther.comMvcFakes

最佳答案

我认为 this thread可以帮助你,你必须模拟 ViewEngine 然后模拟 FindPartialView 调用。

关于c# - 测试函数 "System.Web.Mvc.ViewEngines.Engines.FindPartialView",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8079503/

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