[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?
解决方法
var contents = File.ReadAllText("pathToView"); var result = Razor.Parse(contents,model); // assert here