我試圖學習一些單元測試更復雜的方法。我有一個線性搜索方法,它搜索數組並返回另一個包含「target」索引的數組(如果找到)。我將如何去爲這種方法編寫測試?這裏是下面的方法。單元測試線性搜索方法
public static <T extends Comparable> int[] linearSearch3 (T[] data, T
target)
int count = 0;
int index = 0;
int[] indices = new int[data.length];
for (int i = 0; i < data.length;i++){
if (data[i] == null) break;
if (data[i].compareTo(target) == 0){
indices[count] = i;
count++;
}
}
Arrays.copyOf(indices, count);
int[] copy = Arrays.copyOf(indices,count);
if(count != 0){
return copy;
}
else
return null;
這是我到目前爲止在我的測試方法。這兩個數組是我的測試類的字段。 intArray是我正在搜索的數組。而newArray是我想要返回的數組?然而,我不確定我是否會正確地做這件事。我在第二行得到一個不兼容的類型錯誤。 「不存在類型變量T的實例,因此int []符合其中T是類型變量的整數」。
private final Integer[] intArray = {2, 5, 6, 8, 12, 17, 3, 45, 29, 88, 76, 54,
1, 12, 5, 41, 12, 99};
private final Integer[] newArray = {2};
@Test
public <T extends Comparable> void testLinearSearch3() {
System.out.println("Testing LinearSearch3");
Integer result = Searching.linearSearch3(intArray,(Integer)2);
任何幫助,將不勝感激。謝謝。
我建議在循環前添加一個長度斷言,並將feed assertEquals結果[i]和newArray [i],所以他們可以使用Objects#等同的接口 – Igor