对于我的一个练习,我必须用JUnit测试我的工作。第一次测试没有错误,但其他两个没有错误,但却有失败。 这是什么意思?
public class TestExercise2 {
int [][] numArray = {{3, -1, 4, 0},{5, 9, -2, 6},{5, 3, 7, -8}};
@Test
public void sumOfRows() {
assertEquals(31, Exercise2.sum(numArray));
}
@Test
public void rowsSums() {
int [] i = new int [] {6, 18, 7};
assertArrayEquals(i, Exercise2.rowsSums(numArray));
}
@Test
public void columnSums() {
int [] i = new int [] {13,11,9,-2};
assertArrayEquals(i, Exercise2.columnSums(numArray));
}
答案 0 :(得分:4)
这意味着在其他两个测试用例中测试方法的方法不会按照您的期望返回结果,assertArrayEquals
方法会检查您对您的期望。有关详细信息,请参阅documentation。
答案 1 :(得分:1)
您的断言完全合法且合法,您只需要确保比较两个可比较的阵列。我认为问题在于从Exercise2
方法rowsSums()
和columnSums()
检索错误创建的数组。所以我试图创建这些和几个帮助方法,如getRows()
和getColumns()
。
现在所有测试都会通过!
public class Exercise2 {
public static int getRows(int[][] numArray) {
// if there are no rows, method will simply return 0
return numArray.length;
}
public static int getColumns(int[][] numArray) {
// if there are no rows,
// ArrayIndexOutOfBoundsException will be thrown
// so need to check
if (getRows(numArray) != 0)
return numArray[0].length;
return 0;
}
public static int[] rowsSums(int[][] numArray) {
// getRows(numArray) will return 3
int[] rowsSums = new int[getRows(numArray)];
int sum = 0;
// iterating over an array
for (int i = 0; i < getRows(numArray); i++) {
for (int j = 0; j < getColumns(numArray); j++) {
sum += numArray[i][j];
}
// when row is finished,
// store sum as [i] element of an array
rowsSums[i] = sum;
// setting sum to zero before iterating over next row
sum = 0;
}
return rowsSums;
}
public static int[] columnSums(int[][] numArray) {
// getColumns(numArray) will return 4
int[] columnSums = new int[getColumns(numArray)];
int sum = 0;
// now we iterate over columns first
// so i < getColumns()
for (int i = 0; i < getColumns(numArray); i++) {
for (int j = 0; j < getRows(numArray); j++) {
// swapped i and j
sum += numArray[j][i];
}
// same thing as before
columnSums[i] = sum;
sum = 0;
}
return columnSums;
}
}
您还可以添加sizesOfArray()
测试以验证计算的正确性。
@Test
public void sizesOfArray() {
assertEquals(3, Exercise2.getRows(numArray));
assertEquals(4, Exercise2.getColumns(numArray));
// ArrayIndexOutOfBoundsException will not be thrown
assertEquals(0, Exercise2.getRows(new int[0][0]));
assertEquals(0, Exercise2.getColumns(new int[0][0]));
}