我在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。我有什么想法可以做到这一点吗?
非常感谢!
答案 0 :(得分:9)
首先让我们开始修复您的动作过滤器,因为当前代码看起来很糟糕,而这些演员可能会让您头疼:
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
类具有很强的依赖性。这个不好。进一步的改进是将此功能抽象为一个接口,该接口将被注入动作过滤器的构造函数中。这样您就可以进一步分离应用程序不同层之间的关注点。