我试图在SelectionSort类上理解和实现blackbox / whitebox JUnit技术,但我无法理解要采取的方向..
我在下面尝试失败的尝试之一..我尝试从SelectionSort类测试数组的大小,但我的方法(unsortedArray)无法识别..
@Test
public void testUnsortedArray() {
int n = 20;
int[] x = new int[n];
for (int i = 0; i < 20; i++) {
x[i] = (n);
n--;
i++;
}
SelectionSort2 a = new SelectionSort2();
assertArrayEquals(20, a.unsortedArray(x, 20));
}
以下是我提供的SelectionSort类。非常感谢任何帮助或指导:)
public class SelectionSort2 {
public static void main(String[] args)
{
int n = 20;
int[] numArray = unsortedArray(n); // re-initialize
printArray(numArray,n);
selectSort2(numArray, n);
printArray(numArray, n);
}
//Generate data for the selection sort array
public static int[] unsortedArray(int n) {
int[] a = new int[n];
for (int index = 0; index < n; index++) {
a[index] = (n - index);
}
return a;
}
//print the array
public static void printArray(int[] data, int n)
{
for (int index = 0; index < n; index++) {
System.out.print(data[index] + " ");
}
System.out.println();
}
public static void selectSort2(int[] data, int n)
{
for (int numUnsorted = n; numUnsorted > 0; numUnsorted--) {
int maxIndex = 0;
for (int index = 1; index < numUnsorted; index++) {
if (data[maxIndex] < data[index])
maxIndex = index;
//swap the element
int temp = data[numUnsorted-1];
data[numUnsorted-1] = data[maxIndex];
data[maxIndex] = temp;
}
}
}
}
答案 0 :(得分:1)
黑盒测试可以被设想为输入 - 输出对。您为程序提供一组输入,并查看输出是否符合您的预期。
所以在这种情况下,你会有类似的东西:
input: {5, 3, 1}; expected output: {1, 3, 5}
input: {9, 7, 5, 6, 8, 34, 3, 6}; expected output: {3, 5, 6, 6, 7, 8, 9, 34}
input: {} expected output: {}
input: {1, 3, 5} expected output: {1, 3, 5}
你可以使用像assertArrayEquals()
这样的东西来检查程序的输出是否符合预期。
白盒测试需要更多参与,因为您正在设计试图通过代码执行所有可能路径的测试,这意味着白盒测试往往更具体实现。说实话,我对白盒测试不是很熟悉,所以我可以帮助你。我猜这个白盒测试基本上是在查看你的代码,并寻找在执行过程中可能弹出的各种角落情况。你的代码看起来确实非常简单,所以我不确定你可能会出现哪些黑盒测试尚未涵盖的情况......
对于您提供的具体测试,我认为问题出在这一行:
assertArrayEquals(20, a.unsortedArray(x, 20));
assertArrayEquals()
要么将两个数组作为参数,要么使用String
和两个数组,String
充当错误消息。我认为您的代码不会编译,因为您传递的参数都不是有效的。此外,您似乎没有定义unsortedArray(int[], int)
方法......您的意思是selectSort2(x, 20)
吗?
修复该行后,JUnit测试应该工作。注释掉一行允许JUnit测试至少在我的计算机上运行。
还有一件事 - 你说你想测试SelectionSort类中数组的大小。为此,assertTrue()
可能是使用的方法,但我不确定这样的测试是否有用,因为数组大小无法更改,并且您不会在任何时候返回新数组。
答案 1 :(得分:0)
'assertArrayEquals'方法用于检查2个数组。但是你的第一个参数20不是一个数组对象,可能是失败的原因。