我试图学习一些单元测试更复杂的方法。我有一个线性搜索方法,它搜索数组并返回另一个包含“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