在軟件的開發過程中,我們離不開測試,在這里我首先送給大家兩句關于測試的話keep the bar green to keep the code clear 保持條是綠色則代碼是干凈的
單元測試并不是為了證明你是對的,而是為了證明你沒有錯,下面我就簡單的介紹一下我總結的使用NUnit的一些方法。
如何在Visual Studio.NET 2008中使用NUnit
要在Visual Studio.NET 2008的項目中使用NUnit,首先必須往項目中添加對Nunit框架的引用。方法是在“解決方案資源管理器”窗口中“引用”選項,單擊右鍵,選擇“添加引用”,選擇“.NET”下面的“nunit.framework.dll”,單擊“確定”按鈕,回到“解決方案資源管理器”頁面,可以看到Nunit已經被添加到項目的引用中。如圖所示:
小知識點說明
(1).在使用之前先加入命名空間空間using NUnit.Framework;
(2).代碼通過“[TestFixture]”來標示出測試類,通過“[Test]”標示出測試方法,這樣在測試運行時,NUnit就可以知道這些類和方法是需要測試的,則加載運行單元測試。通過Assert類中的AreEqual方法來判斷測試是否通過。如下:
//用TestFixture標示出測試列
[TestFixture]
public class NunitTestClass
{
//用Test標示出測試方法
[Test]
public void TestAddTestClass()
{
Form1 form = new Form1();
int a = 1;
int b = 2;
int expcted = 3;
int actual = form.Add(1, 2);
Assert.AreEqual(expcted, actual);
}
}
(3).測試結果通過的類或方法則以綠色標注,不通過的類或方法以紅色標注。黃色表示某些測試被忽略。
Nunit簡單屬性總結
(1).[TestFixture] 表示這是一個測試類
(2).[Test] 表示這是一個測試方法
(3). [SetUp] 只要一個函數被標記為[SetUp]屬性的話,那么它就會在每一個測試的這些函數或者這些Case進行之前都要去運行一次。它用來在測試之前進行一個初始化的作用。
(4). [TearDown]結束建立,資源回收,每個方法都執行一次。
(5).[TestFixtureSetUp] 表示整個類的初始化,在函數最先執行的時候運行一次。
(6).[TestFixtureTearDown] 表示銷毀整個類的初始化,在函數最后呢執行的時候只運行一次。
(7).[Test,Explicit] 顯示運行,在Nunit測試器中不選中則不運行,選中的話則會運行
(8).[Test] [Ignore(“this case is ignored”)] 忽略當前這個Case,不讓其運行,在Nunit測試其中顯示的是黃色。Ignored后面的字符串是為了在Nunit測試其中提示這個信息。
(9).[Test] [Category(GroupName)] 把下面的case歸納在整個組里面,在NUnit里面選中組的話只顯示組里面包含的函數。
下面是一個簡單的例子:整型冒泡排序的實現及測試
/*在Calculator中寫入如下的方法
*整型冒泡排序的實現及測試
*/
public int[] BubbleSort(int[] array)
{
if (null == array)
{
Console.Error.WriteLine("Parameter should't be null");
return new int[] { };
}
for (int i = 0; i < array.Length - 1;++i)
{
bool swap = false;
for (int j = 0; j < array.Length - i - 1; ++j)
{
if (array[j] > array[j + 1])
{
int temp = array[j]; //簡單的一個交換
array[j] = array[j + 1];
array[j + 1] = temp;
swap = true;
}
}
if (!swap)
{
return array;
}
}
return array;
}
在測試類CalculatorTest中輸入如下的信息:
[Test]
[Category("GroupBubbleSort")]
public void TestBubbleSort()
{
int[] array = { 1,4,4,4,4, 8, 4, 6, 5, 9 };
int[] result = cal.BubbleSort(array);
int[] Expected = { 1, 4,4,4,4,4, 5, 6, 8, 9 };
Assert.AreEqual(Expected, result);
}
[Test]
[Category("GroupBubbleSort")]
public void TestBubbleSort1()
{
int[] array = null;
int[] result = cal.BubbleSort(array);
int[] excepted = { };
Assert.AreEqual(excepted, result);
}
[Test]
[Category("GroupBubbleSort")]
public void TestBubbleSort2()
{
int[] array = { };
int[] result = cal.BubbleSort(array);
int[] excepted = { };
Assert.AreEqual(excepted, result);
}
堆棧實例測試知識點
[Test,ExpectedException] 表示期望這個函數拋出一個異常。
新建MyStack類,在類里面模擬實現一些堆棧的知識點代碼如下: