[英]Java Unit Testing
我有一個程序,正在嘗試為其編寫單元測試,我只需要知道它是否正確? 這是程序:
public static int[] bucketSort(int[] entries)
{
int numberBuckets = maxVal(entries);
//Creates an array with maxVal buckets.
int[] buckets = new int[numberBuckets+1];
//Loop through input entries and add one to the count for every occurrence of that number in entries.
for (int i = 0; i < entries.length; i++)
{
buckets[entries[i]]++;
}
int key = 0;
for (int i = 0; i < buckets.length; i++)
{
for (int j = 0; j < buckets[i]; j++)
{
//Use the number of every occurrence of each number in entries to construct the sorted array.
entries[key] = i;
key++;
}
}
//Print out the sorted array.
for(int i = 0; i <= entries.length-1; i++)
{
System.out.print(entries[i] + ", ");
}
return entries;
}
這是單元測試的內容
import junit.framework.Assert;
import junit.framework.TestCase;
public void testBucketSort()
{
int[] a1 = {9, 6, 2, 2, 4, 1, 0, 10,};
int[] a2 = BucketSort.bucketSort(a);
int[] a3 = {0, 1, 2, 2, 4, 6, 9, 10,};
Assert.assertArrayEquals(a2, a3);
}
}
不,這是不正確的。 有兩個原因:
您已使用已排序的數據。 盡管它也應該是一個測試用例,但是您應該使用隨機數據集並對其進行排序。 保留另一個數組,如a3作為預期數組,然后在a2和a3上調用assertArrayEquals。
您的assertArrayEquals實現未驗證任何內容。 基本上,它只打印true或false,但是您的測試始終會通過。 您可以使用Assert類中的junit assertArrayEquals方法,也可以使用自己的實現,如果條件不匹配,則應通過失敗測試。
除非您有充分的理由,否則請使用JUnit,而不是您自己的測試方法。
另外,請考慮一下您的代碼可能如何中斷並為每種情況編寫測試。 例:
確保在所有情況下結果都正確正確的長度並正確排序。
我看到的最大問題是,您以錯誤的順序將參數傳遞給assertArrayEquals()
:所有JUnit斷言都按預期的 實際順序接受參數。
除此之外,您沒有足夠的測試。 對於任何基於數組的方法,我至少要編寫4個測試:一個帶有0個元素的測試,一個帶有1個元素,一個帶有2個元素,以及一個帶有3個元素的測試。這將捕獲大多數邊緣情況(0、1、2),並且至少給出確保您的代碼可以正常處理不斷增加的大小(3)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.