我在SO上进行了搜索,看起来这个问题经常被问到.我已经能够使模拟工作,我也能够执行OnActionExecuted()而没有任何问题.这是我的单元测试.评论的行是失败的,我敢肯定我没有嘲笑正确的类型.
//Arrange //var viewResult = new ViewResult(); var filterContextMock = new Mock<ActionExecutedContext>(); var routeData = new RouteData(); var httpContextMock = new Mock<HttpContextBase>(); routeData.Values["data"] = "Mock data"; var requestContext = new RequestContext(httpContextMock.Object,routeData); var controller = new FakeController(); controller.ControllerContext = new ControllerContext(requestContext,controller); filterContextMock.Setup(f => f.RouteData).Returns(routeData); filterContextMock.Setup(f => f.Controller).Returns(controller); //filterContextMock.Setup(f => f.Result).Returns(viewResult); //Act var wrapFilterAttribute = new WrapFilterAttribute(); wrapFilterAttribute.OnActionExecuted(filterContextMock.Object);
这是我的动作过滤器.
public class WrapFilterAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { var view = (ViewResultBase)filterContext.Result; if (view != null) { Baseviewmodel viewmodel = (Baseviewmodel)view.ViewData.Model ?? new Baseviewmodel(); viewmodel.Wrap = new WrapperFactory().GetWrap(); } base.OnActionExecuted(filterContext); } }
我在这里遇到的问题是filterContext.Result总是以EmptyResult形式出现.我想改为使用含水的ViewResult.我有什么想法可以做到这一点?
非常感谢!
解决方法
首先让我们从修复你的动作过滤器开始,因为当前代码看起来很糟糕,这些演员可能会让你头疼:
public class WrapFilterAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { var view = filterContext.Result as ViewResultBase; if (view != null) { // the controller action returned a ViewResultBase var viewmodel = view.ViewData.Model as Baseviewmodel; if (viewmodel != null) { // the model passed to the view was derived from // Baseviewmodel so we can safely update the Wrap // property viewmodel.Wrap = new WrapperFactory().GetWrap(); } } base.OnActionExecuted(filterContext); } }
单元测试:
// arrange var sut = new WrapFilterAttribute(); var filterContextMock = new Mock<ActionExecutedContext>(); var viewResultMock = new Mock<ViewResultBase>(); filterContextMock.Object.Result = viewResultMock.Object; var viewmodel = new Baseviewmodel(); viewResultMock.Object.ViewData.Model = viewmodel; // act sut.OnActionExecuted(filterContextMock.Object); // assert // TODO: assert something on the viewmodel.Wrap property like // for example that it has been initialized
备注:您的动作过滤器对WrapperFactory类有很强的依赖性.这个不好.进一步的改进是将此功能抽象为一个接口,该接口将被注入动作过滤器的构造函数中.这将允许您进一步分离应用程序的不同层之间的关注点.