如何使用NUnit進行單元測試

 轉:http://www.cnblogs.com/xugang/archive/2008/02/26/1082565.html
這篇文章是我學習《單元測試之道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)

 


本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/xiaokuang513204/archive/2009/10/27/4734453.aspx

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章