如何测试ASP.Net MVC视图?

时间:2021-07-19 04:13:12

I want to write a unit test to ensure that the view I am returning is the correct one.

我想写一个单元测试,以确保我返回的视图是正确的。

My plan is to write a test that first invokes the controller and then calls the ActionResult method I plan to test I thought I could write something like

我的计划是编写一个首先调用控制器的测试,然后调用我计划测试的ActionResult方法我以为我可以编写像

Controller controller = new HomeController();
var actionresult = controller.Index();
Assert.False(actionresult.ToString(), String.Empty);

which would then allow me to parse the actionresult for the test value. However I cannot directly instantiate the public ActionResult Index() method.

这将允许我解析测试值的actionresult。但是我无法直接实例化公共ActionResult Index()方法。

How do I do this?

我该怎么做呢?

2 个解决方案

#1


Here's an example from Professional ASP.NET MVC 1.0 (book):

这是Professional ASP.NET MVC 1.0(书籍)的一个例子:


[TestMethod]
public void AboutReturnsAboutView()
{
     HomeController controller = new HomeController();
     ViewResult result = controller.About() as ViewResult;

     Assert.AreEqual("About", result.ViewName);
}

Note that this will fail if you don't return an explicit view in your controller method, i.e. do this:

请注意,如果您未在控制器方法中返回显式视图,则会失败,即执行以下操作:


     Return(View("About"));

not this:


     Return(View());

Or the test won't pass. You should only need to do this if your method will ever return more than one view, otherwise you should return an implicit view anyway and not bother testing the framework.

或者测试不会通过。如果你的方法将返回多个视图,你应该只需要这样做,否则你应该返回一个隐式视图,而不是打扰测试框架。

#2


The test helpers in MVCContrib will help you here.

MVCContrib中的测试助手将在这里为您提供帮助。

ViewResult result = controller.Index().AssertViewRendered().ForView("Blah");

#1


Here's an example from Professional ASP.NET MVC 1.0 (book):

这是Professional ASP.NET MVC 1.0(书籍)的一个例子:


[TestMethod]
public void AboutReturnsAboutView()
{
     HomeController controller = new HomeController();
     ViewResult result = controller.About() as ViewResult;

     Assert.AreEqual("About", result.ViewName);
}

Note that this will fail if you don't return an explicit view in your controller method, i.e. do this:

请注意,如果您未在控制器方法中返回显式视图,则会失败,即执行以下操作:


     Return(View("About"));

not this:


     Return(View());

Or the test won't pass. You should only need to do this if your method will ever return more than one view, otherwise you should return an implicit view anyway and not bother testing the framework.

或者测试不会通过。如果你的方法将返回多个视图,你应该只需要这样做,否则你应该返回一个隐式视图,而不是打扰测试框架。

#2


The test helpers in MVCContrib will help you here.

MVCContrib中的测试助手将在这里为您提供帮助。

ViewResult result = controller.Index().AssertViewRendered().ForView("Blah");