首页 > 编程语言 >无涯教程-ASP.NET MVC - 单元测试

无涯教程-ASP.NET MVC - 单元测试

时间:2023-10-12 18:31:47浏览次数:47  
标签:ASP Employees 单元测试 无涯 System new Employee using public

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

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

单元测试的目标

单元测试的主要目标是采用应用程序中最小的可测试软件,并确定其行为是否完全符合您的预期。在将每个单元集成到模块中以测试模块之间的接口之前,需要分别测试每个单元。

让我们看一个简单的单元测试示例,在该示例中,我们使用单元测试创​​建了一个新的ASP.NET MVC应用程序。

步骤1 - 打开Visual Studio,然后单击File→New→Item菜单选项。

将打开一个"New Project"对话框。

New Project Dialog

步骤2 - 在左窗格中,选择 Templates > Visual C# > Web.

步骤3 - 在中间窗格中,选择ASP.NET Web应用程序。

步骤4 - 在"Name"字段中输入项目名称" MVCUnitTestingDemo",然后单击"OK"继续。您将看到以下对话框,要求您设置ASP.NET项目的初始内容。

MVCUnitTestingDemo

步骤5 - 选择MVC作为模板,不要忘记选中对话框底部的"Add unit tests"复选框。

通过Visual Studio创建项目后,您将在"Solution Explorer"窗口中看到许多文件和文件夹。

步骤6 - 您可以看到Solution Explorer中有两个项目。一个是ASP.NET Web项目,另一个是单元测试项目。

Web Project

步骤7 - 运行此应用程序,您将看到以下输出。

Run Web Project

如上面的屏幕截图所示,导航栏上有"Home","About"和"Contact"按钮。选择"About",您将看到以下视图。

About Select

选择"Contact",然后弹出以下屏幕。

Contact Select

现在,我们扩展" MVCUnitTestingDemo"项目,您将在Controllers文件夹下看到HomeController.cs文件。

HomeController.cs file

HomeController包含三种操作方法,如以下代码所示。

using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;
using System.Web.Mvc;

namespace MVCUnitTestingDemo.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文件。

MVCUnitTestingDemo.Test

在这个HomeControllerTest类中,您将看到三个方法,如以下代码所示。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;

using MVCUnitTestingDemo;
using MVCUnitTestingDemo.Controllers;

namespace MVCUnitTestingDemo.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);
      }
   }
}

这三种方法将测试"About"和"Contact"操作方法是否正常工作。要测试这三种操作方法,请转到"Test"菜单。

Test Menu

选择Run→All Tests to test 这些操作方法。

Action Methods

现在,您将在左侧看到"Test Explorer",您可以在其中看到所有测试均已通过,让我们添加另一种操作方法,该方法将列出所有员工。首先,我们需要在Models文件夹中添加一个employee类。

以下是Employee类的实现。

using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;

namespace MVCUnitTestingDemo.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。右键单击Solution Explorer中的controller文件夹,然后选择Add→Controller。

它将显示"Add Scaffold"对话框。

Add Scaffold

选择" MVC 5 Controller–Empty"选项,然后单击"Add"按钮,将出现"Add Controller"对话框。

将名称设置为EmployeeController,然后单击"Add"按钮。

Add Controller EmployeeController

您将在Controllers文件夹中看到一个新的C#文件" EmployeeController.cs",该文件已打开,可以在Visual Studio中进行编辑。让我们使用以下代码更新EmployeeController。

using MVCUnitTestingDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;
using System.Web.Mvc;

namespace MVCUnitTestingDemo.Controllers {
   public class EmployeeController : Controller{
      [NonAction]
		
      public List<Employee> GetEmployeeList(){
         return new List<Employee>{
            new Employee{
               ID = 1,
               Name = "Allan",
               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 = "Carson",
               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);
      }
   }
}

要添加"Employees View"操作方法,请右键单击"Employees"操作,然后选择"Add View…"。

Employee Action

您将看到默认的视图名称。从模板下拉列表中选择"List",从模型类下拉列表中选择"Employee",然后单击确定。

现在,我们需要添加链接"Employees"列表,让我们打开"Views/Shared"文件夹下的_layout.cshtml文件,然后在"Contact"链接下方添加"employees"链接。

<li>@Html.ActionLink("Employees List", "Employees", "Employee")</li>

以下是_layout.cshtml的完整实现。

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "utf-8" />
      <meta name = "viewport" content = "width=device-width, initial-scale=1.0">
      <title>@ViewBag.Title - My ASP.NET Application</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" datatoggle =
                  "collapse" data-target = ".navbar-collapse">
                  <span class = "icon-bar"></span>
                  <span class = "icon-bar"></span>
                  <span class = "icon-bar"></span>
               </button>
					
               @Html.ActionLink("Application name", "Index", "Home", new
                  { area="" }, new { @class="navbar-brand" })
            </div>
				
            <div class = "navbar-collapse collapse">
               <ul class = "nav navbar-nav">
                  <li>@Html.ActionLink("Home", "Index", "Home")</li>
                  <li>@Html.ActionLink("About", "About", "Home")</li>
                  <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                  <li>@Html.ActionLink("Employees List", "Employees", "Employee")</li>
               </ul>
					
               @Html.Partial("_LoginPartial")
            </div>
				
         </div>
			
      </div>
		
      <div class = "container body-content">
         @RenderBody()
         <hr />
         <footer>
            <p>© @DateTime.Now.Year - My ASP.NET Application</p>
         </footer>
      </div>
		
      @Scripts.Render("~/bundles/jquery")
      @Scripts.Render("~/bundles/bootstrap")
      @RenderSection("scripts", required: false)
		
   </body>
</html>

要从Employee控制器测试Employees操作方法,我们需要在单元测试项目中添加另一种测试方法。在EmployeeControllerTest类之后,我们将在其中测试Employees操作方法。

[TestClass]
public class EmployeeControllerTest{
   [TestMethod]
   public void Employees(){
      //Arrange
      EmployeeController controller = new EmployeeController();
		
      //Act
      ViewResult result = controller.Index() as ViewResult;
		
      //Assert
      Assert.IsNotNull(result);
   }
}

从"Test"菜单中选择"Run"→"All Tests"以测试这些操作方法。

Employee Test Method

您可以看到Employees测试方法现在也已通过。运行应用程序时,将看到以下输出。

点击导航栏中的"Employees List"选项,您将看到员工列表。

Employee List

参考链接

https://www.learnfk.com/asp.net_mvc/asp.net-mvc-unit-testing.html

标签:ASP,Employees,单元测试,无涯,System,new,Employee,using,public
From: https://blog.51cto.com/u_14033984/7834615

相关文章

  • 一种有效的嵌入式软件单元测试工具
     一、引言在当今的软件开发领域,单元测试已经成为确保代码质量,提升软件可靠性和安全性的重要环节。对于嵌入式软件来说,尤其在汽车控制等安全性至关重要的领域,单元测试更成为不可或缺的一部分。然而,传统的单元测试方法往往效率低下且容易出错。为了解决这一问题,本文介绍了一种有......
  • 无涯教程-ASP.NET MVC - 模型绑定
    ASP.NETMVC模型绑定允许您将HTTP请求数据与模型进行映射,使用浏览器在HTTP请求中发送的数据创建.NET对象的过程。模型绑定是HTTP请求和C#操作方法之间精心设计的桥梁,由于POST和GET会自动传输到您指定的数据模型中,因此开发人员可以轻松使用表单上的数据,ASP.NETMVC使用默认联编......
  • 无涯教程-ASP.NET MVC - 选择器
    ActionSelector是可以应用于Action方法的属性,用于响应请求而调用哪种Action方法,它有助于路由引擎选择正确的操作方法来处理特定请求。在编写Action方法时,它起着至关重要的作用。这些选择器将根据操作方法来决定方法调用的行为,它通常用于为操作方法的名称加上别名。ActionSele......
  • 无涯教程-ASP.NET MVC - 控制器
    控制器本质上是ASP.NETMVC应用程序的中央单元,控制器决定将选择哪个模型,然后在呈现该视图之后,从模型中获取数据并将其传递给相应的视图。控制器是从System.Web.Mvc.Controller继承的C#类,System.Web.Mvc.Controller是内置的控制器基类,控制器中的每个公共方法都称为操作方法,这意味......
  • nittest单元测试框架—加载测试用例的3种方法以及测试报告存储管理
     项目结构 测试用例importunittestclassLoginTestCase(unittest.TestCase):deftest_login_success(self):self.assertEqual({'code':200,'msg':'登录成功'},self.login('kobe','666'))deftest_......
  • 无涯教程-ASP.NET MVC - 简介
    ASP.NETCoreMVC是ASP.NETCore内,提供给Web应用程序开发的框架,它可视为ASP.NETMVC的后继版本,其主要功能均衍生自ASP.NETMVC,但它除了基于ASP.NETCore外,也将ASP.NETMVC与类似平台进行了整合,例如负责View的ASP.NETWebPages以及负责RESTfulAPI的ASP.NETW......
  • 无涯教程-ASP.NET Core - Razor表单
    在本章中,无涯教程将继续讨论标签助手,还将在应用程序中添加新功能,并使其能够编辑现有员工的详细信息,将在每个员工添加一个链接,该链接将转到HomeController上的Edit动作。@modelHomePageViewModel@{ViewBag.Title="Home";}<h1>Welcome!</h1><table>@forea......
  • 无涯教程-ASP.NET Core - Razor导入
    在本章中,无涯教程将讨论RazorViewImport,除了ViewStart文件之外,还有一个ViewImports文件,MVC框架在呈现任何视图时都将查找该文件。就像ViewStart文件一样,可以将ViewImports.cshtml放到文件夹中,并且ViewImports文件可以影响文件夹层次结构中的所有视图。此视图是此版本MVC的......
  • 使用GoogleTest框架进行cpp代码的基本单元测试
    title:aliases:tags:-cpp/单元测试-cmake-工程技术category:-方法stars:url:creation-time:2023-10-1119:02modification-time:这里主要介绍从0开始实现基本的单元测试功能。构建首先从googletest代码仓下载源码。网上很多指导包括官方的指......
  • 无涯教程-ASP.NET Core - Razor视图
    在本章中,无涯教程将讨论RazorViewStart。MVC中的Razor视图引擎有一个约定,即它将查找名称为_ViewStart.cshtml的任何文件,并在该文件中执行代码。ViewStart文件中的代码无法呈现到页面的HTML输出中,但可用于从各个视图内的代码块中删除重复的代码。在示例中,如果希望每个视图......