c# – 我如何在单元测试中模拟控制器上下文,以便我对字符串函数的部分视图有效?

前端之家收集整理的这篇文章主要介绍了c# – 我如何在单元测试中模拟控制器上下文,以便我对字符串函数的部分视图有效?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试为我的控制器创建一个单元测试,但是我正在测试的动作使用部分视图来进行字符串函数,该函数不希望在我的测试中工作.
private string RenderPartialViewToString(string viewName,object model = null)
{
   if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetrequiredString("action");

   ViewData.Model = model;

   using (System.IO.StringWriter sw = new System.IO.StringWriter())
   {
      ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,viewName);
      ViewContext viewContext = new ViewContext(ControllerContext,viewResult.View,ViewData,TempData,sw);
      viewResult.View.Render(viewContext,sw);

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

这给我一个错误“对象引用未设置为对象的实例”在行上ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,viewName);

我在控制器的单元测试中的设置是(删除几位以简化它):

var mock = new Mock<ControllerContext>();
mock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName);
if (userName != null)
{
   mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);
   mock.SetupGet(p => p.HttpContext.User.Identity.IsAuthenticated).Returns(true);
}
else
{
   mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(false);
}
var controller = new BlogController();
controller.ControllerContext = mock.Object;

我没有任何运气试图找到解决方案或解决方案.任何帮助赞赏.谢谢.

如我所建议的,我已经尝试设置路由数据,但仍然收到错误.这是我添加的:

var routeData = new RouteData();
routeData.Values.Add("controller","BlogController");
mock.SetupGet(m => m.RouteData).Returns(routeData);

解决方法

最后的解决方案,由于在评论中的帮助.
var mock = new Mock<ControllerContext>();
mock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName);
if (userName != null)
{
   mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);
   mock.SetupGet(p => p.HttpContext.User.Identity.IsAuthenticated).Returns(true);
}
else
{
   mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(false);
}

var routeData = new RouteData();
routeData.Values.Add("controller","BlogController");
mock.SetupGet(m => m.RouteData).Returns(routeData);

var view = new Mock<IView>();
var engine = new Mock<IViewEngine>();
var viewEngineResult = new ViewEngineResult(view.Object,engine.Object);
engine.Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(),It.IsAny<string>(),It.IsAny<bool>())).Returns(viewEngineResult);
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(engine.Object);

var controller = new BlogController();
controller.ControllerContext = mock.Object;
原文链接:https://www.f2er.com/csharp/92306.html

猜你在找的C#相关文章