加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 单元测试ViewEngines.Engines.FindView的正确方

发布时间:2020-12-16 09:58:30 所属栏目:asp.Net 来源:网络整理
导读:我最近对我的mvc应用程序进行了一些重构,并意识到返回了很多静态视图.而不是让多个控制器具有仅返回视图的操作结果,我决定创建一个控制器,如果它们存在则返回静态视图,如果视图不存在则抛出404错误. public ActionResult Index(string name){ ViewEngineResu
我最近对我的mvc应用程序进行了一些重构,并意识到返回了很多静态视图.而不是让多个控制器具有仅返回视图的操作结果,我决定创建一个控制器,如果它们存在则返回静态视图,如果视图不存在则抛出404错误.

public ActionResult Index(string name)
{
    ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext,name,null);

    if (result.View == null)
        ThrowNotFound("Page does not exists.");

    return View(name);
}

我的问题是单元测试的正确方法是什么?我尝试了下面的代码,但我得到的错误是“RouteData必须包含一个名为’controller’且具有非空字符串值的项”.

[Theory]
[InlineData("ContactUs")]
public void Index_should_return_view_if_view_exists(string name)
{
    controller = new ContentController();
    httpContext = controller.MockHttpContext("/","~/Content/Index","GET"); ;

    var result = (ViewResult)controller.Index(name);

    Assert.NotNull(result.View);
}

我的目的是让单元测试出去并获取真实的视图.然后我开始怀疑是否应该使用SetupGet为FindView模拟ViewEngines并创建两个测试,其中第二个测试如果视图为null则抛出未找到的异常.

测试此功能的正确方法是什么?任何指针,示例代码或博客文章都会有所帮助.

谢谢

解决方法

您应该创建一个模拟的视图引擎并将其放入集合中:

[Theory]
[InlineData("ContactUs")]
public void Index_should_return_view_if_view_exists(string name)
{
    var mockViewEngine = MockRepository.GenerateStub<IViewEngine>();
    // Depending on what result you expect you could set the searched locations
    // and the view if you want it to be found
    var result = new ViewEngineResult(new [] { "location1","location2" });
    // Stub the FindView method
    mockViewEngine
        .Stub(x => x.FindView(null,null,false))
        .IgnoreArguments()
        .Return(result);
    // Use the mocked view engine instead of WebForms
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(mockViewEngine);

    controller = new ContentController();

    var actual = (ViewResult)controller.Index(name);

    Assert.NotNull(actual.View);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读