单元测试自定义视图引擎

MrJ*_*rJD 3 c# asp.net-mvc unit-testing asp.net-mvc-4

我正在尝试对我编写的自定义视图引擎进行单元测试.

视图引擎的预期功能是它改变了执行FindView时RazorViewEngine基本所在的位置

这是我的单元测试

public void ViewEngineReturnsDependencyView()
{
    //Mock http request
    var mockRequest = new Mock<HttpRequestBase>();
    //Mock server variable
    NameValueCollection variables = new NameValueCollection();
    variables.Add("APPL_PHYSICAL_PATH", TEST_APPLICATION_PATH);
    mockRequest.Setup(r => r.ServerVariables).Returns(variables);

    //Mock http context
    var mockHttpContext = new Mock<HttpContextBase>();

    //Mock route
    mockHttpContext.Setup(c => c.Request).Returns(mockRequest.Object);
    var routeData = new RouteData();
    routeData.Values.Add("controller", "testController");
    routeData.Values.Add("action", "testAction");

    //Mock controller context
    var controllerContext = new testController().ControllerContext;
    controllerContext.HttpContext = mockHttpContext.Object;
    controllerContext.RouteData = routeData;
    var mockControllerContext = new ControllerContext(mockHttpContext.Object,
                        routeData, 
                        new Mock<ControllerBase>().Object);

    //Run find view
    viewEngine.FindView(mockControllerContext, "TestView", null, false);
}
Run Code Online (Sandbox Code Playgroud)

恼人地viewEngine.FindView(...);抛出异常:

测试方法...抛出异常:System.NullReferenceException:对象引用未设置为对象的实例.结果StackTrace:

在System.Web.WebPages.DisplayModeProvider.GetDisplayMode(HttpContextBase context)

在System.Web.Mvc.VirtualPathProviderViewEngine.GetPathFromGeneralName(ControllerContext controllerContext,List`1位置,String name,String controllerName,String areaName,String cacheKey,String []&searchingLocations)

在System.Web.Mvc.VirtualPathProviderViewEngine.GetPath(ControllerContext controllerContext,String [] locations,String [] areaLocations,String locationsPropertyName,String name,String controllerName,String cacheKeyPrefix,Boolean useCache,String []&searchingLocations)

在System.Web.Mvc.VirtualPathProviderViewEngine.FindView(ControllerContext controllerContext,String viewName,String masterName,Boolean useCache)

at ... Mvc.CustomRazorViewEngine.FindView(ControllerContext controllerContext,String viewName,String masterName,Boolean useCache)in ...\Mvc\CustomRazorViewEngine.cs:line 85

at ... Tests.MVC.ViewEngine.ViewEngineReturnsDependencyView()in ... Tests\MVC\ViewEngine.cs:第78行

我的问题是,如何创建适当的模拟单元测试RazorViewEngine.FindView()?

hai*_*770 6

System.Web.WebPages.DisplayModeProvider.GetDisplayMode()方法正在使用该HttpContext.Items属性,您还需要模拟该属性.

尝试:

mockHttpContext.Setup(c => c.Items).Returns(new Dictionary<object, object>());
Run Code Online (Sandbox Code Playgroud)