先建立一個類庫,名稱爲Largest,用於尋找最大數
using System.Collections.Generic;
using System.Text;
namespace Largest
{
public class Cmp
{
public static int Largest(int[] list)
{
int index, max = Int32.MinValue;
if (list.Length == 0)
{
throw new ArgumentException("largest:Empty list");
}
for (index = 0; index <= list.Length - 1; index++)
{
if (list[index] > max)
{
max = list[index];
}
}
return max;
}
}
}
接着創建測試單元。方法:在上面的頁面空白處右鍵選擇創建單元測試,接着系統自動創建了一個測試項目。下面修改代碼,以便更好的查看測試過程
//int expected = 0;
//int actual;
//actual = Largest.Cmp.Largest(list);
//Assert.AreEqual(expected, actual, "Largest.Cmp.Largest 未返回所需的值。");
//Assert.Inconclusive("驗證此測試方法的正確性。");
Assert.AreEqual(9, Largest.Cmp.Largest(new int[] { 8, 9, 7 }));
Assert.AreEqual(9, Largest.Cmp.Largest(new int[] { 9, 8, 7 }));
Assert.AreEqual(9, Largest.Cmp.Largest(new int[] { 7, 8, 9 }));
Assert.AreEqual(9, Largest.Cmp.Largest(new int[] { 9, 7, 9, 8 }));
Assert.AreEqual(1, Largest.Cmp.Largest(new int[] {1}));
Assert.AreEqual(-7, Largest.Cmp.Largest(new int[] { -8, -9, -7 }));
然後運行測試項目,可以查看測試結果