使用 assertArrayEquals 使用 JUnit 进行测试时出错
Error when testing with JUnit using assertArrayEquals
测试这段代码时:
public static int maxRowAbsSum(int[][] array) {
int[][] maxRowValue = {
{3, -1, 4, 0},
{5, 9, -2, 6},
{5, 3, 7, -8}
};
int maxRow = 0;
int indexofMaxRow = 0;
for (int row = 0; row < maxRowValue.length; row++) {
int totalOfRow = 0;
for (int column = 0; column < maxRowValue[row].length; column++){
if (maxRowValue[row][column] > 0) {
totalOfRow += maxRowValue[row][column];
} else {
totalOfRow -= maxRowValue[row][column];
}
}
if (totalOfRow > maxRow) {
maxRow = totalOfRow;
indexofMaxRow = row;
}
}
System.out.println("Row " + indexofMaxRow + " has the sum of " + maxRow);
return indexofMaxRow;
}
使用此 JUnit 代码:
@Test
public void maxRowAbsSum() {
int [] i = new int [] {};
assertArrayEquals(i, Exercise2.maxRowAbsSum(numArray));
}
这用红色下划线表示 assertArrayEquals:
The method assertArrayEquals(int[], int[]) in the type Assert is not applicable for the arguments (int[], int)
我是不是写错了?我如何使用 JUnit 对其进行测试以使其没有错误或故障?
您正在尝试将 int
(int[]
) 的数组与来自 maxRowAbsSum()
方法的单个 int
return 进行比较。这是行不通的,它是在将苹果与橙子进行比较,而 JUnit 会使用它的方法签名来防止您遇到这种情况。
您应该编写测试以匹配 maxRowAbsSum()
方法 return 类型,例如:
@Test
public void shouldCalculateMaxRowAbsSum() {
int expected = 3; // example value, change to match your test scenario
assertEquals(expected, Exercise2.maxRowAbsSum(numArray));
}
i 是一个 int 数组,而 Exercise2.maxRowAbsSum(numArray) returns int。
比较它们是不可能的,因此是错误的。
我修复了我的代码,但仍然使用 Karol 的示例:
而不是 return indexOfMaxRow
只返回具有最大值的行的索引,我将其更改为 return maxRow
这返回了 23 而不是 JUnit 期望的 2。
测试这段代码时:
public static int maxRowAbsSum(int[][] array) {
int[][] maxRowValue = {
{3, -1, 4, 0},
{5, 9, -2, 6},
{5, 3, 7, -8}
};
int maxRow = 0;
int indexofMaxRow = 0;
for (int row = 0; row < maxRowValue.length; row++) {
int totalOfRow = 0;
for (int column = 0; column < maxRowValue[row].length; column++){
if (maxRowValue[row][column] > 0) {
totalOfRow += maxRowValue[row][column];
} else {
totalOfRow -= maxRowValue[row][column];
}
}
if (totalOfRow > maxRow) {
maxRow = totalOfRow;
indexofMaxRow = row;
}
}
System.out.println("Row " + indexofMaxRow + " has the sum of " + maxRow);
return indexofMaxRow;
}
使用此 JUnit 代码:
@Test
public void maxRowAbsSum() {
int [] i = new int [] {};
assertArrayEquals(i, Exercise2.maxRowAbsSum(numArray));
}
这用红色下划线表示 assertArrayEquals:
The method assertArrayEquals(int[], int[]) in the type Assert is not applicable for the arguments (int[], int)
我是不是写错了?我如何使用 JUnit 对其进行测试以使其没有错误或故障?
您正在尝试将 int
(int[]
) 的数组与来自 maxRowAbsSum()
方法的单个 int
return 进行比较。这是行不通的,它是在将苹果与橙子进行比较,而 JUnit 会使用它的方法签名来防止您遇到这种情况。
您应该编写测试以匹配 maxRowAbsSum()
方法 return 类型,例如:
@Test
public void shouldCalculateMaxRowAbsSum() {
int expected = 3; // example value, change to match your test scenario
assertEquals(expected, Exercise2.maxRowAbsSum(numArray));
}
i 是一个 int 数组,而 Exercise2.maxRowAbsSum(numArray) returns int。 比较它们是不可能的,因此是错误的。
我修复了我的代码,但仍然使用 Karol 的示例:
而不是 return indexOfMaxRow
只返回具有最大值的行的索引,我将其更改为 return maxRow
这返回了 23 而不是 JUnit 期望的 2。