gpt4 book ai didi

asp.net - 单元测试操作过滤器 - 如何模拟 ViewResult

转载 作者:行者123 更新时间:2023-12-02 20:09:29 26 4
gpt4 key购买 nike

我对 SO 进行了搜索,看起来这个问题经常被问到。我已经能够让模拟工作,并且我也能够毫无问题地执行 OnActionExecuted() 。这是我的单元测试。注释行是失败的行,我确信我没有 mock 正确的类型。

        //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 类有很强的依赖性。不是很好。进一步的改进是将这个功能抽象到一个接口(interface)中,该接口(interface)将被注入(inject)到 Action 过滤器的构造函数中。这将使您能够进一步分离应用程序不同层之间的关注点。

关于asp.net - 单元测试操作过滤器 - 如何模拟 ViewResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3840400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com