我在我的 ASP.NET MVC 3 项目中使用 T4MVC。我有以下基本测试:
[TestMethod]
public void IndexReturnsIndexView()
{
var controller = new HomeController();
var result = controller.Index();
result.AssertViewRendered().ForView(MVC.Home.Views.Index);
}
如果控制器方法返回默认视图,则测试失败:
public virtual ActionResult Index()
{
return View();
}
给出的错误是:
MvcContrib.TestHelper.ActionResultAssertionException: Expected view name '~/Views/Home/Index.cshtml', actual was ''
但是,如果我覆盖View
指定viewName
要返回的内容,则测试通过:
public virtual ActionResult Index()
{
return View(MVC.Home.Views.Index);
}
我尝试使用以下断言,但仍然不走运:
result.AssertViewRendered().ForView(MVC.Home.Index().GetT4MVCResult().Action);
引发以下错误:
MvcContrib.TestHelper.ActionResultAssertionException: Expected view name 'Index', actual was ''
然后我意识到我误读了断言失败,所以我将测试更改为:
result.AssertViewRendered().ForView(String.Empty);
测试通过了,但测试本身似乎毫无用处。
最好我不想按名称指定所有视图,那么我该如何测试呢?为了澄清,我使用的是我今天从 NuGet 安装的MvcContrib.Mvc3.TestHelper-ci 3.0.96.0 。
更新
这不是问题的答案,但我已经开始执行以下操作,这提供了作为测试用例的更多价值:
using (var controller = new FeatureController(mockGateway))
{
// Act
var result = controller.Index();
var model = result.ViewData.Model as MyModel;
// Assert
Assert.IsNotNull(model, "Model is null or wrong type");
result.AssertViewRendered().WithViewData<MyModel>();
// Alternative Assert for model data
Assert.IsTrue(model.Items.Count > 0);
}