如何安裝 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 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 的引用才能編譯。
[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)
文章來源于領測軟件測試網 http://www.kjueaiud.com/