65.9K
CodeProject 正在变化。 阅读更多。
Home

如何使用 VSTS 编写单元测试用例

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.50/5 (5投票s)

2009年2月11日

CPOL

4分钟阅读

viewsIcon

89053

downloadIcon

678

Visual Studio Team System (VSTS) 附带了内置的测试工具,这些工具提供了更有效和更高效的方式来为 Windows 和 Web 应用程序编写测试脚本。

VSTS 概述

Visual Studio Team System (VSTS) 附带了内置的测试工具,这些工具提供了更有效和更高效的方式来为 Windows 和 Web 应用程序编写测试脚本。

VSTS 用于管理大型项目。要使用该系统,我们必须设置一个服务器并进行安装,并维护所有用户的访问权限。如果用户位于远程位置,我们需要打开防火墙才能访问。

VSTS 还允许开发人员聚合多个已编写的测试,以便自动化测试代理可以执行这些测试,从而模拟高达一千个用户的负载测试。可以同时运行多个代理,以大约一千个用户为单位来增加负载。整个过程允许团队重用为各种测试而启动的工作。

这使得开发人员自己更容易基于单个代码模块的单元测试来执行负载测试,从而可以及早发现问题,节省时间,并学会如何编写更好的代码。

使用 ASP.NET 单元测试,我们可以测试属于 ASP.NET 网站的类和方法。这通常与其他任何事物的测试非常相似,因为我们可以对站点 App_Code 目录中的类进行代码生成。不幸的是,由于 Visual Studio 处理这些文件的方式不同,因此无法为页面类本身(定义在页面的 .aspx.aspx.cs 文件中)生成测试。

CreateUTC.JPG

VSTS 支持五种关键类型的测试

  • 单元测试,其中我们调用一个类并验证其行为是否符合预期。
  • 手动测试。
  • 通用测试,它使用一个现有的测试应用程序作为最大测试的一部分运行。
  • Web 测试,以确保 HTML 应用程序正常运行。
  • 负载测试,以确保应用程序具有可伸缩性。

示例

using Microsoft.VisualStudio.QualityTools.UnitTesting.Framework;
using System;
namespace Test
{
   /// <summary>
   ///This is a test class for VSTTDemo.LogonInfo and is intended
   ///to contain all VSTTDemo.LogonInfo Unit Tests
   ///</summary>
   [TestClass()]
   public class LogonInfoTest
   {
      private TestContext testContextInstance;
      /// <summary>
      ///Gets or sets the test context which provides
      ///information about and functionality for the 
      ///current test run.
      ///</summary>
      public TestContext TestContext
      {
         get
         {
            return testContextInstance;
         }
         set
         {
            testContextInstance = value;
         }
      }

      /// <summary>
      ///Initialize() is called once during test execution before
      ///test methods in this test class are executed.
      ///</summary>
      [TestInitialize()]
      public void Initialize()
      {
         //  TODO: Add test initialization code
      }

      /// <summary>
      ///Cleanup() is called once during test execution after
      ///test methods in this class have executed unless
      ///this test class' Initialize() method throws an exception.
      ///</summary>
      [TestCleanup()]
      public void Cleanup()
      {
         
         //  TODO: Add test cleanup code
      }


      // ...

      [TestMethod]
      // ...
      public void ChangePasswordTest()
      {   
      // ...
      }

   }
}

测试设置和清理方法分别使用 TestInitializeAttributeTestCleanupAttribute 进行装饰。在这些方法中的每一个中,我们都可以放置需要在每次测试之前或之后运行的任何附加代码。这意味着在每次执行 ChangePasswordTest()(对应于 LogonInfoTest 表中的每个记录)之前,将执行 Initialize()Cleanup()。每次执行 NullUserIdInConstructorEmptyUserIdInConstructor 时也会发生同样的情况。

可以使用此类方法在数据库中插入默认数据,然后在测试结束时清理数据。例如,可以在 Initialize() 中开始一个事务,然后在清理过程中回滚该事务,这样,假设测试方法使用相同的连接,数据状态将在每次测试执行结束时恢复。类似地,可以操作测试文件。

在调试过程中,TestCleanupAttribute 装饰的方法可能由于调试器在清理代码执行之前停止而不会运行。因此,通常最好在测试设置期间检查清理,并在必要时优先执行清理。其他可用于初始化和清理的测试属性是 AssemblyInitializeAttribute/AssemblyCleanupAttributeClassInitializeAttribute/ClassCleanupAttribute。程序集相关的属性只运行一次,而类相关的属性在加载特定测试类时各运行一次。

方法

为了使用 VSTS 对示例应用程序进行单元测试并解决 HttpContext 和 Session 相关问题,我们应遵循下面提到的步骤。下面的示例伪代码在示例应用程序中强调了涉及的步骤。

Sample.aspx.cs 的伪代码

using System.Diagnostics;
using System.Web.Hosting;
using System.Web;
using System.IO;
using System.Security.Permissions;
using System.Web.SessionState;

HttpContext Object Initialization

private TestContext testContextInstance;
 
public TestContext TestContext
{
    get { return testContextInstance; }
    set { testContextInstance = value; }
}

Page 对象可以通过类的 TestContext 对象的 RequestedPage 属性访问。由于页面在加载时实际类型是动态生成的,我们只能将其提供为 Page 类型的对象,但仍然可以访问页面子类的成员。

Session 初始化和调用

[AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, 
 Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, 
 Level = AspNetHostingPermissionLevel.Minimal)]
public interface IRequiresSessionState { }

[TestInitialize]
public void TestInit()
{
    HttpContext.Current = new HttpContext(new HttpRequest("", 
                          "https://", ""), 
                          new HttpResponse(new System.IO.StringWriter()));
    System.Web.SessionState.SessionStateUtility.AddHttpSessionStateToContext(
               HttpContext.Current, new HttpSessionStateContainer("",
               new SessionStateItemCollection(),  new HttpStaticObjectsCollection(), 
               20000, true, HttpCookieMode.UseCookies, SessionStateMode.Off, false));

    //Initialize your specific application custom Context Class.
    //Initialize User object initialized
}

[TestMethod()]
[DeploymentItem("Application.Web.dll")]
public void LoadTest()
{
    Test target = new Test ();
    TestProject1.ObjectName  accessor = new TestProject1.ObjectName (target);
        // write the test cases for the method.
}

示例测试用例项目

/// <summary>
///This is a test class for _DefaultTest and is intended
///to contain all _DefaultTest Unit Tests
///</summary>
[TestClass()]
public class _DefaultTest
{

    private TestContext testContextInstance;

    [TestInitialize]
    public void TestInit()
    {
        HttpContext.Current = new HttpContext(new HttpRequest("", 
                              "https://", ""), 
                              new HttpResponse(new System.IO.StringWriter()));
        System.Web.SessionState.SessionStateUtility.AddHttpSessionStateToContext(
                   HttpContext.Current, new HttpSessionStateContainer("",
                   new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 
                   20000, true, HttpCookieMode.UseCookies, SessionStateMode.Off, false));

        //Initialize your specific application custom Context Class.
        //Initialize User object initialized
    }

    /// <summary>
    ///Gets or sets the test context which provides
    ///information about and functionality for the current test run.
    ///</summary>
    public TestContext TestContext
    {
        get
        {
            return testContextInstance;
        }
        set
        {
            testContextInstance = value;
        }
    }

    /// <summary>
    ///A test for Page_Load
    ///</summary>
    [TestMethod()]
    [UrlToTest("https://")]
    [DeploymentItem("SampleProject.dll")]
    public void Page_LoadTest()
    {
        // TODO: Initialize to an appropriate value
        _Default_Accessor target = new _Default_Accessor();
        // TODO: Initialize to an appropriate value
        object sender = null;
        // TODO: Initialize to an appropriate value
        EventArgs e = null;
        target.Page_Load(sender, e);
    }

    /// <summary>
    ///A test for SetSession
    ///</summary>
    [TestMethod()]
    [DeploymentItem("SampleProject.dll")]
    public void SetSessionTest()
    {
        // TODO: Initialize to an appropriate value
        _Default_Accessor target = new _Default_Accessor();
        target.SetSession();
    }
}

关于 Web.config

使用 VSTS 进行单元测试时,将不支持 Web.config。因此,我们应该将 Web.config 的所有内容(除 system.web 外)复制并粘贴到 App.config 中。然后应将 App.config 放在测试项目文件夹中。

调试测试用例

使用 System.Diagnostics.Debugger.Break(); 来调试应用程序。

Void TestMethod()
{
    System.Diagnostics.Debugger.Break();
    //Some Statement
}

在 VS2008 中,只需右键单击并生成测试用例。它会自动为所有方法/选定的方法生成测试用例,并处理具有属性的会话问题。

© . All rights reserved.