在電腦編程中,單元測試是一種軟體測試方法,通過這種方法對各個源代碼單元進行測試,以確定它們是否適合使用。 換句話說,這是一個軟體開發過程,在這個過程中,應用程式中最小的可測試部分(稱為單元)被單獨和獨立地審查以便正確執行和操作。
在程式編程中,一個單元可以是一個完整的模組,但更常見的是一個單獨的功能或過程。 在面向對象編程中,一個單元通常是一個完整的介面,比如一個類,但可能是一個單獨的方法。
單元測試通常是自動的,但也可以手動完成。
單元測試的目標
單元測試的主要目標是在應用程式中使用最小的可測試軟體,並確定其行為是否與期望的完全一致。每個單元在將它們集成到模組之前分別進行測試,以測試模組之間的介面。
我們來看一個單元測試的簡單例子,在這個例子中使用單元測試選項來創建一個新的ASP.NET MVC應用程式。
第1步 - 打開Visual Studio,然後單擊:檔 -> 新建 -> 專案 菜單選項。一個新的專案對話框打開。
第2步 - 在左側窗格中,選擇:範本 -> Visual C# -> Web 。
第3步 - 在中間窗格中,選擇:ASP.NET Web應用程式。
第4步 - 在名稱字段中輸入專案名稱為:MVCUnitTesting,然後單擊確定 繼續。
然後將看到下麵的對話框,要求設置ASP.NET專案的初始內容。
第5步 - 選擇MVC作為範本,不要忘記選中對話框底部的添加單元測試複選框。也可以更改測試專案名稱,但在此示例中,我們將其保持原樣,因為它是默認名稱。
專案由Visual Studio創建後,將在“解決方案資源管理器”窗口中看到許多檔和文件夾。
第6步 - 可以看到在解決方案資源管理器中有兩個專案。 一個是ASP.NET Web專案,另一個是單元測試專案。
第7步 - 運行這個應用程式,會看到下麵的輸出。
如上圖所示,導航欄上有“首頁”,“關於”和“聯繫人”按鈕。這裏點擊“關於”鏈接,會看到下麵的視圖。
現在展開MVCUnitTestingDemo 專案,將看到 Controllers 檔夾下的HomeController.cs 檔。
HomeController 包含三個操作方法,如下面的代碼所示。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCUnitTesting.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
展開MVCUnitTestingDemo.Tests 專案,Controllers檔夾下的HomeControllerTest.cs檔。
在這個HomeControllerTest
類中有三個方法,如下面的代碼所示。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MVCUnitTesting;
using MVCUnitTesting.Controllers;
namespace MVCUnitTesting.Tests.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
[TestMethod]
public void About()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.About() as ViewResult;
// Assert
Assert.AreEqual("Your application description page.", result.ViewBag.Message);
}
[TestMethod]
public void Contact()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Contact() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
}
這三個方法將測試Index
,About
和Contact
操作方法是否正常工作。要測試這三個操作方法,請轉到測試 菜單。選擇:運行 -> 所有測試 項來測試這些操作方法。
現在會看到左邊的測試資源管理器,可以看到所有的測試都通過了。再添加一個動作方法,它用於列出所有的員工。首先,需要在Models 檔夾中添加一個Employee
類。
以下是Employee
類的實現 -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCUnitTesting.Models
{
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime JoiningDate { get; set; }
public int Age { get; set; }
}
}
添加EmployeeController 。 右鍵單擊解決方案資源管理器 中的Controllers 檔夾,然後選擇:添加 -> 控制器 ,它將顯示“添加基架”對話框。選擇:MVC 5控制器 - 空 選項,然後點擊“添加” 按鈕,如下圖所示 -
添加控制器對話框將出現。將名稱設置為:EmployeeController,然後單擊“添加”按鈕。
在Controllers 檔夾中看到一個新的 C# 檔 - EmployeeController.cs
,該檔夾在Visual Studio中打開並進行編輯。這裏使用下麵的代碼更新 EmployeeController
。
using MVCUnitTesting.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCUnitTesting.Controllers
{
public class EmployeeController : Controller
{
[NonAction]
public List<Employee> GetEmployeeList()
{
return new List<Employee>{
new Employee{
ID = 1,
Name = "Maxsu",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 23
},
new Employee{
ID = 2,
Name = "Carson",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 45
},
new Employee{
ID = 3,
Name = "Kobe Bryant",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 37
},
new Employee{
ID = 4,
Name = "Laura",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 26
},
};
}
// GET: Employee
public ActionResult Index()
{
return View();
}
public ActionResult Employees()
{
var employees = from e in GetEmployeeList()
orderby e.ID
select e;
return View(employees);
}
}
}
要為Employee
操作方法添加視圖,請右鍵單擊Employees
方法並選擇:添加視圖…
您將看到視圖的默認名稱。從“範本”下拉列表中選擇“List”,從“模型類”下拉列表中選擇“Employee”,然後單擊“確定”。
現在需要添加一個鏈接到Employees
列表,打開Views/Shared 檔夾下的_layout.cshtml 檔,並在聯繫人 鏈接下面添加員工列表 鏈接。
<li>@Html.ActionLink("員工列表", "Employees", "Employee")</li>
以下是_layout.cshtml 的完整實現 -
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - 我的 ASP.NET 應用程式</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("應用程式名稱", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("主頁", "Index", "Home")</li>
<li>@Html.ActionLink("關於", "About", "Home")</li>
<li>@Html.ActionLink("聯繫方式", "Contact", "Home")</li>
<li>@Html.ActionLink("員工列表", "Employees", "Employee")</li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - 我的 ASP.NET 應用程式</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
要從Employee
控制器測試Employees
動作方法,需要在單元測試專案中添加另一個測試方法。在HomeControllerTest.cs
檔中的EmployeeControllerTest
類代碼之後,如下所示 -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MVCUnitTesting;
using MVCUnitTesting.Controllers;
namespace MVCUnitTesting.Tests.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
[TestMethod]
public void About()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.About() as ViewResult;
// Assert
Assert.AreEqual("Your application description page.", result.ViewBag.Message);
}
[TestMethod]
public void Contact()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Contact() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
[TestClass]
public class EmployeeControllerTest
{
[TestMethod]
public void Employees()
{
// Arrange
EmployeeController controller = new EmployeeController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
}
從測試 菜單中選擇:運行 -> 所有測試 項來測試這些操作方法。
可以看到Employees
測試方法現在也通過了。運行應用程式時將看到以下輸出。
點擊導航欄中的“員工列表”選項,將看到員工列表資訊,如下圖所示 -