正如标题所述,我期待着就如何适当测试控制员的延伸方向。 延期导致部分观点,而Im则使用JSONResult:
public static string RenderPartialViewToString(this Controller controller, string viewName = null, object model = null)
{
if (string.IsNullOrEmpty(viewName))
{
viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
}
controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
例常使用:
public JsonResult Foo()
{
var model = _repository.getSomeData();
return Json(new { html = this.RenderPartialViewToString("Index", model) }, JsonRequestBehavior.AllowGet);
}
I m using NUnit & the MvcContrib test helper,然而,在设置一名控制器时,利用这一延伸Im 进入NRE。 我假定控制者的背景没有正确确定?
归根结底,测试是在<代码>上进行的。 ViewEngines.Engines.Find PartialView。 这里是失败测试的一部分:
var routeData = new RouteData();
routeData.Values.Add("controller", "someName");
routeData.Values.Add("action", "someAction");
var builder = new TestControllerBuilder();
var controller = new ListingController(repository.Object);
builder.RouteData = routeData;
builder.InitializeController(controller);
var result = controller.Foo();