首先,让我们从修复操作过滤器开始,因为当前代码看起来很糟糕,而这些铸件可能会给您带来麻烦:
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
班级。这不好。进一步的改进是将此功能抽象到一个接口中,该接口将被注入到动作过滤器的构造函数中。这将允许您在应用程序的不同层之间进一步分离关注点。