Unit testing my controller method results in an empty ViewName?

后端 未结 4 874
情歌与酒
情歌与酒 2020-12-29 21:18

I\'m doing some simple MS unit tests on my standard, nothing special controller.

When I check the ViewName proprty, from the returned ViewResult

4条回答
  •  醉梦人生
    2020-12-29 22:12

    The ViewName is only present when you set it in the ViewResult. If your View name matches your controller name, then I would check to ensure that the ViewName is null or empty as that would be (IMO) the correct behavior since you wouldn't want to set a name on the view. I only check that the ViewName is set when I intend that the View to be returned does not match the action -- say, when returning the "Error" view, for example.

    EDIT: The following is the source for ExecuteResult in ViewResultBase.cs (from RC1, I don't have the source for RTW on my Macintosh). As you can see it checks to see if the ViewName has been set directly and if not, it pulls it from the action in the controller context's route data. This only happens in ExecuteResult, which is invoked AFTER your controller's action has completed.

        public override void ExecuteResult(ControllerContext context) {
            if (context == null) {
                throw new ArgumentNullException("context");
            }
            if (String.IsNullOrEmpty(ViewName)) {
                ViewName = context.RouteData.GetRequiredString("action");
            }
    
            ViewEngineResult result = null;
    
            if (View == null) {
                result = FindView(context);
                View = result.View;
            }
    
            ViewContext viewContext = new ViewContext(context, View, ViewData, TempData);
            View.Render(viewContext, context.HttpContext.Response.Output);
    
            if (result != null) {
                result.ViewEngine.ReleaseView(context, View);
            }
        }
    

提交回复
热议问题