0
点赞
收藏
分享

微信扫一扫

如何使用NUnit进行单元测试

南柯Taylor 2022-03-31 阅读 52

这篇文章是我学习《单元测试之道C#版》这本书籍所做的笔记,所以内容存在非原创性。


NUnit 是一个免费开源的(http://www.nunit.org)产品,它提供了一套测试框架和一个测试运行程序(test runner)。
​注意:test tunner 知道如何寻找具有 [TestFixture] 属性的类和类中的 [Test] 方法。


如何安装 NUnit:


方法一:​下载 NUnit 的C# 源码并自己编译,并安装在计算机上;

方法二:​使用Microsoft Installer (MSI)文件。

注意:MSI只内置在Windows 2000以上,Windows NT或以下版本,需要在www.microsoft.com 中搜索“Microsoft Installer Redistributable”。


使用 test tunner 的3种方法:

1. NUnit GUI

   它提供一个独立的NUnit 图形化工具。

   从菜单Tool/Options中的个性化设置来打开Visual Studio支持。


2. NUnit 的命令行​   

   需要配置Path运行环境。


3. Visual Studio 的插件
​   有几种能把NUnit 集成到Visual Studio的插件,诸如 http://www.mutantdesign.co.uk/nunit-addin/



简单示例

一、在VS中创建一个类型为Class Library 的新项目
​TestNUnit.csproj


二、代码类:创建一个名为Largest.cs的代码类文件

public class Cmp

{

   public static int Largest( int[] list)

   {

         int index;

         int max = Int32.MinValue; //若 max=0; 则在list的元素为负数的时候运行错误


         //list的长度为0,也就是list数组为空的时候,抛出一个运行期异常

         if(list.length == 0)

         {

          throw new ArgumentException("largest: Empty list");

         }


         for(index = 0;index < list.length; index++)

         {

            if(list[index] > max) max = list[index];

         }

         return max;

   }

}

三、测试类:创建一个名为TestLargest.cs的测试类文件

注意:测试代码使用了Nunit.Framework,因此需要增加一个指向nunit.framework.dll 的引用才能编译。

using Nunit.Framework;

[TestFixture]


public class TestLargest

{

  [Test]

  public void LargestOf3()

  {

    Assert.AreEqual(9,Cmp.Largest(new int[]{7,8,9} )); // 测试“9”在最后一位

    Assert.AreEqual(9,Cmp.Largest(new int[]{7,9,8} )); // 测试“9”在中间位

    Assert.AreEqual(9,Cmp.Largest(new int[]{9,7,8} )); // 测试“9”在第一位

    Assert.AreEqual(9,Cmp.Largest(new int[]{9,9,8} )); // 测试存在重复的“9”

    Assert.AreEqual(9,Cmp.Largest(new int[]{9} ));     // 测试list中只存在“9”一个元素


    // 测试list中负数的存在,若类Cmp中Largest方法的 int max=0; 则会检测抱错

    Assert.AreEqual(-7,Cmp.Largest(new int[]{-9,-8,-7} ));

  }


  [Test, ExpectedException(typeof(ArgumentException))]

  public void TestEmpty()

  {

    // 测试list数组为空(长度为0)时,是否抛出异常

    Cmp.Largest(new int[] {});

  }

}


生成解决方案(快捷键 Ctrl+Shift+B)



附加:

单元测试之道C#版--使用NUnit     书籍原代码下载:http://www.pragmaticprogrammer.com/sk/ut/

举报

相关推荐

0 条评论