如何测试局部视图在C#中的ASP.NET MVC中呈现 [英] How to test PARTIAL view was rendered in C# ASP .NET MVC

查看:164
本文介绍了如何测试局部视图在C#中的ASP.NET MVC中呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个观点,它具有使内部的局部视图:

 < D​​IV CLASS =partialViewDiv>
    @ Html.RenderPartial(部分,Model.SomeModelProperty);
< / DIV>

和一个控制器,它返回这个观点

 公众的ActionResult动作()
        {
            ...
            VAR模型=新SomeModel(){SomeModelProperty =someValue中}
            返回视图(视图,模型);
        }

如何测试观点呈现,我知道:

  [TestMethod的]
公共无效TestView()
{
   ...
   VAR的结果= controller.Action();   //断言
   result.AssertViewRendered()ForView(意见)WithViewData< SomeModel>();
}

但是当我打电话

<$p$p><$c$c>result.AssertPartialViewRendered().ForView(\"partial\").WithViewData<SomeModelPropertyType>();

我收到此错误信息

 预期结果是类型PartialViewResult的。它实际上是一个类型的ViewResult的。

我在做什么错了?


解决方案

  

我在做什么错了?


您正在测试的控制器:这种测试本质上嘲笑的观点,只是验证控制器返回预期视图(和型号)。

由于视野中的视图呈现的PartialView部分不参与测试,所以无法测试其是否在做你所期望的。

在一般情况下,大多数人都没有单元测试的意见;但如果你想这样做看看这个博客或谷歌MVC单元测试视图

I have a view and it has partial view rendering inside:

<div class="partialViewDiv">
    @Html.RenderPartial("partial", Model.SomeModelProperty);
</div>

And a controller, which returns this view

public ActionResult Action()
        {
            ...
            var model = new SomeModel(){SomeModelProperty = "SomeValue"}
            return View("view", model);
        }

How to test view was rendered i know:

[TestMethod]
public void TestView()
{
   ...
   var result = controller.Action();

   // Assert
   result.AssertViewRendered().ForView("view").WithViewData<SomeModel>();
}

but when I call

result.AssertPartialViewRendered().ForView("partial").WithViewData<SomeModelPropertyType>();

I get this error message

Expected result to be of type PartialViewResult. It is actually of type ViewResult.

What am I doing wrong?

解决方案

What am I doing wrong?

You're testing the controller: such tests essentially mock the view and just verify that the controller is returning the expected view (and model).

Because the View "view" that renders the PartialView "partial" is not involved in the testing, so you can't test whether it's doing what you expect.

In general, most people don't unit test Views; but if you want to do so look at this blog or google for "MVC unit test view"

这篇关于如何测试局部视图在C#中的ASP.NET MVC中呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆