[Test] public voID Exampletest(){ var reportModel = new ReportModel(); var reportHTML = RenderRazorVIEw( @"..\..\Report.Mvc\VIEws\Report\Index.csHTML",reportModel); Assert.IsFalse( string.IsNullOrEmpty(reportHTML),"VIEw Failed to Render!"); } public string RenderRazorVIEw(string vIEwPath,object model){ //WHAT GOES HERE? }
我已经在网络上看到了很多有关这方面的信息,但它要么反对测试竞争,要么只能在Web请求的上下文中使用.
> Arguing Against – Unit Testing the Views? – 结论是视图中没有逻辑,所以你只需要测试编译.我认为测试VIEw是有价值的,以确保没有Null引用异常,显示正确的部分等.
> Web请求的上下文 – Render a view as a string – 这是为了呈现要在电子邮件中发送的视图.但是这种方法需要通过Web请求(即有效的httpContextBase)进行调用.
我一直在努力使Render a view as a string适应Mocked httpContextBase,但在使用Mocked ControllerContext时遇到了问题:
Object reference not set to an instance of an object.
at System.Web.WebPages.displayModeProvIDer.GetdisplayMode(httpContextBase context)
at System.Web.Mvc.ControllerContext.get_displayMode()
at System.Web.Mvc.VirtualPathProvIDerVIEwEngine.GetPath(ControllerContext controllerContext,String[] locations,String[] areaLocations,String locationspropertyname,String name,String controllername,String cacheKeyPrefix,Boolean useCache,String[]& searchedLocations)
这是我到目前为止的代码:
public string RenderRazorVIEw(string vIEwPath,object model) { var controller = GetMockedDummyController(); //Exception here var vIEwResult = VIEwEngines.Engines.FindVIEw(controller.ControllerContext,"Index",""); using (var sw = new StringWriter()) { var vIEwContext = new VIEwContext( controller.ControllerContext,vIEwResult.VIEw,new VIEwDataDictionary(model),new TempDataDictionary(),sw); vIEwResult.VIEw.Render(vIEwContext,sw); return sw.ToString(); } }
我正在构建控制器:
private Controller GetMockedDummyController() { var httpContextBaseMock = new Mock<httpContextBase>(); var httpRequestMock = new Mock<httpRequestBase>(); var httpResponseMock = new Mock<httpResponseBase>(); httpContextBaseMock.SetupGet(x => x.Request).Returns(httpRequestMock.Object); httpContextBaseMock.SetupGet(x => x.Response).Returns(httpResponseMock.Object); var controller = new DummyController(); var routeData = new RouteData(); routeData.Values.Add("controller","Dummy"); controller.ControllerContext = new ControllerContext( httpContextBaseMock.Object,routeData,controller); controller.Url = new UrlHelper( new RequestContext( httpContextBaseMock.Object,routeData),new RouteCollection()); return controller; }
DummyController只是公共类DummyController:Controller {}
题
提供VIEw的路径,如何从Test项目将其呈现为HTML?或者更具体地说,我如何模拟出ControllerContext.displayMode?
解决方法 假设您完全分离了关注点,是否有必要实例化控制器?如果没有,那么也许您可以使用 RazorEngine来测试您的视图.var contents = file.ReadAllText("pathToVIEw"); var result = Razor.Parse(contents,model);// assert here总结
以上是内存溢出为你收集整理的c# – 在单元测试期间渲染视图 – ControllerContext.DisplayMode全部内容,希望文章能够帮你解决c# – 在单元测试期间渲染视图 – ControllerContext.DisplayMode所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)