原文地址:http://weblogs.asp.net/stephenwalther/archive/2008/06/17/asp-net-mvc-tip-3-provide-explicit-view-names-when-unit-testing.aspx
摘要:在這個Tip中,Stephen Walther解釋了當控制器action需要返回一個特定的視圖時,應該如何進行單元測試。他建議你如果打算建立單元測試的話,還是要明確地指出視圖的名稱。
ASP.NET MVC架構是一個高度可測試的架構。你可以很方便地測試MVC控制器Action,確定它是否能夠返回你所期望的結果。在這個Tip中,我會向你展示如何測試一個會返回特定視圖的控制器action。
考慮清單1中名為HomeController的MVC控制器。該控制器包含一個名為Index()的action。Index() action返回一個視圖。然而,這裡並沒有提供視圖的名字。視圖的名字是通過控制器action的名字推斷出來的。因此,當你到用Index() action時,會返回名為Index的視圖。
HomeController還包含另外一個名為Index2()的action。這個action也返回一個視圖。然而,這個action明確地指出了視圖的名字。視圖的名字被傳遞到View()方法中。該控制器action和第一個控制器action做的事情是相同的。然而,第一個控制器action的視圖名字是推斷出來的,而第二個控制器action的視圖名字是明確指定的。
清單1 - HomeController.cs
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Web;
5using System.Web.Mvc;
6
7namespace Tip3.Controllers
8{
9 public class HomeController : Controller
10 {
11 public ActionResult Index()
12 {
13 return View(); // view name inferred
14 }
15
16 public ActionResult Index2()
17 {
18 return View("Index"); // view name explicit
19 }
20
21
22 }
23}
如果你計劃為ASP.NET MVC應用程式建立單元測試,則你必需明確指定視圖的名字。否則,即便返回了正確的視圖,也無法通過單元測試。
清單2的測試類別中包含了兩個測試方法。第一個方法測試了HomeController的Index() action,第二個方法測試了Index2()。第一個測試總是失敗,而第二個測試則能成功(參見圖1)。
清單2 - HomeControllerTest.cs
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Web.Mvc;
6using Microsoft.VisualStudio.TestTools.UnitTesting;
7using Tip3;
8using Tip3.Controllers;
9
10namespace Tip3Tests.Controllers
11{
12 /**//// <summary>
13 /// Summary description for HomeControllerTest
14 /// </summary>
15 [TestClass]
16 public class HomeControllerTest
17 {
18 [TestMethod]
19 public void Index()
20 {
21 // Arrange
22 HomeController controller = new HomeController();
23
24 // Act
25 ViewResult result = controller.Index() as ViewResult;
26
27 // Assert
28 Assert.AreEqual("Index", result.ViewName);
29 }
30
31
32 [TestMethod]
33 public void Index2()
34 {
35 // Arrange
36 HomeController controller = new HomeController();
37
38 // Act
39 ViewResult result = controller.Index2() as ViewResult;
40
41 // Assert
42 Assert.AreEqual("Index", result.ViewName);
43 }
44
45
46 }
47}
圖1 - 單元測試結果
單元測試無法推斷視圖名字。我的建議是,如果打算進行單元測試,應該總是明確指定視圖的名字。
此處下載原始碼:http://weblogs.asp.net/blogs/stephenwalther/Downloads/Tip3/Tip3.zip。
------
廣告:歡迎光臨[.NETRegex庫] http://regex-lib.net/。