ASP.Net MVC单元测试

在计算机编程中,单元测试是一种软件测试方法,通过这种方法对各个源代码单元进行测试,以确定它们是否适合使用。 换句话说,这是一个软件开发过程,在这个过程中,应用程序中最小的可测试部分(称为单元)被单独和独立地审查以便正确执行和操作。

在程序编程中,一个单元可以是一个完整的模块,但更常见的是一个单独的功能或过程。 在面向对象编程中,一个单元通常是一个完整的接口,比如一个类,但可能是一个单独的方法。

单元测试通常是自动的,但也可以手动完成。

单元测试的目标

单元测试的主要目标是在应用程序中使用最小的可测试软件,并确定其行为是否与期望的完全一致。每个单元在将它们集成到模块之前分别进行测试,以测试模块之间的接口。

我们来看一个单元测试的简单例子,在这个例子中使用单元测试选项来创建一个新的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);
        }
    }
}

这三个方法将测试IndexAboutContact操作方法是否正常工作。要测试这三个操作方法,请转到测试 菜单。选择:运行 -> 所有测试 项来测试这些操作方法。

现在会看到左边的测试资源管理器,可以看到所有的测试都通过了。再添加一个动作方法,它用于列出所有的员工。首先,需要在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测试方法现在也通过了。运行应用程序时将看到以下输出。

点击导航栏中的“员工列表”选项,将看到员工列表信息,如下图所示 -


上一篇: ASP.Net MVC Bootstrap 下一篇: ASP.Net MVC自托管(本地主机部署)