我有一个包含交换两个变量方法的类。该方法不返回任何值。
public void swap(int a, int b) {
a ^= b;
b = a ^ b;
a = a ^ b;
}
我该如何使用JUnit进行测试?它甚至不会引起任何副作用。
没有任何需要测试的内容。
这个方法什么也不做:它返回void
,并且没有任何副作用(不会改变数据,...)。
public void swap(int[] a, int[] b) {
a[0] ^= b[0];
b[0] = a[0] ^ b[0];
a[0] = a[0] ^ b[0];
}
public void swap(int a, int b) {
a ^= b;
b = a ^ b;
a = a ^ b;
}
将值放入长度为1的数组中,然后执行交换操作所建议的函数将起作用,因为数组是按引用传递的。
public void swap(int[] a, int[] b) {
a[0] ^= b[0];
b[0] = a[0] ^ b[0];
a[0] = a[0] ^ b[0];
}
然而,如果数组a和b都指向同一个数组,则该函数将失败。上述函数将使传递为两个参数的数组的零元素为零。因此,我们需要按以下方式更改上述函数:
public void swap(int[] a, int[] b) {
if (a == b) { //do not swap
return;
}
if (a ==null) {
return;
}
if (b ==null) {
return;
}
a[0] ^= b[0];
b[0] = a[0] ^ b[0];
a[0] = a[0] ^ b[0];
}
我会为上述代码建议一些 Junit 测试用例。您可以使用 JUnit 包中的 assertEquals() 方法来测试 a[1] 和 b[1] 中的值是否已交换。
//both a[0] and b[0] are different values
int[] a = {4};
int[] b = {5};
int copy_a = a[0];
int copy_b = b[0];
swap(a, b);
assertEquals("copy_a should be b[0]", copy_a, b[0]);
assertEquals("copy_b should be a[0]", copy_b, a[0]);
//both a[0] and b[0] are same values
a[0] = 4;
b[0] = 4;
copy_a = a[0];
copy_b = b[0];
swap(a, b);
assertEquals("copy_a should be copy_b", copy_a == copy_b, a[0] == b[0]);
//case when you pass same array as both arguments.
a[0] = 9;
copy_a = a[0];
swap(a, a);
assertEquals("copy_a should be a[0]", copy_a, a[0]);