有這麼一個計算數組最大值的方法.
namespace NUnitTest
{
public class MathCompute
{
public int Largest(int[] array)
{
if (null == array || 0 == array.Length)
{
throw new Exception("參數傳遞錯誤");
}
int largest = Int32.MinValue;
foreach (int element in array)
{
if (element > largest)
{
largest = element;
}
}
return largest;
}
}
}
我們寫一段測試代碼,使用NUnit的TestCaseSource屬性測試它.
namespace NUnitTest
{
[TestFixture]
public class MathComputeTest
{
private MathCompute mc;
[TestFixtureSetUp]
public void Init()
{
mc = new MathCompute();
}
[Test, TestCaseSource("LargestCases")]
public void TestLargest(int[] arr,int expected)
{
Assert.AreEqual(expected,mc.Largest(arr));
}
#region 資料部分
static object[] LargestCases =
{
new object[] {new int[]{1,2,3,4},4},
new object[] {new int[]{-2, -3, -5, -9},-2},
new object[] {new int[]{1},1},
new object[] {new int[]{20,20,20,20},20},
//new object[] {new int[]{},null}
};
#endregion
}
}
上面的代碼提供了4組資料當做測試案例.
運行一下:測試成功通過,如.
下面使用TestCaseSource的另一個建構函式
TestCaseSourceAttribute(Type sourceType, string sourceName);
寫如下測試代碼
[Test, TestCaseSource(typeof(Class1), "LargestTestCases")]
public int TestLargest(int[] arr)
{
return mc.Largest(arr);
}
資料來源類
class Class1
{
static IEnumerable<TestCaseData> LargestTestCases
{
get
{
yield return new TestCaseData(new int[] { 1, 2, 3, 4 }).Returns(4);
yield return new TestCaseData(new int[] { -2, -3, -5, -9 }).Returns(-2);
yield return new TestCaseData(new int[] { 1, 2, 0, -1, -2 }).Returns(2);
yield return new TestCaseData(new int[] { 1 }).Returns(1);
yield return new TestCaseData(new int[] { 20, 20, 20 }).Returns(20);
yield return new TestCaseData(new int[] { })
.Throws(typeof(Exception))
.SetName("參數傳遞錯誤")
.SetDescription("參數錯誤");
}
}
}
運行一下:測試結果如下
顯而易見,TestCaseSource不僅可以提供多個測試案例進行測試,同時也把測試代碼和測試資料有效地分離,
,便於管理和更新測試資料。
但是,也有一個問題。就是每次修改資料後都要進行編譯才能更新資料。效率不高。
Question:能否把資料存放在XML檔案裡,定義好資料的Type和Value,讓程式動態載入、初始化資料,然後傳給測試程式。
這樣我就可以直接改XML裡的資料,而不用管代碼如何如何了。
希望各位路過的部落格園大大們給小弟指點一下。
參考資料:NUnit Documentation