【问题标题】:Error when testing with JUnit using assertArrayEquals使用 assertArrayEquals 使用 JUnit 进行测试时出错
【发布时间】:2018-04-12 13:02:59
【问题描述】:

在测试这段代码时:

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 说:

Assert 类型中的方法assertArrayEquals(int[], int[]) 不适用于参数(int[], int)

我写错了吗?如何使用 JUnit 对其进行测试,使其没有错误或故障?

【问题讨论】:

    标签: java testing junit junit4


    【解决方案1】:

    i 是一个 int 数组,而 Exercise2.maxRowAbsSum(numArray) 返回 int。 无法比较它们,因此会出现错误。

    【讨论】:

      【解决方案2】:

      您正在尝试将 int (int[]) 的数组与从 maxRowAbsSum() 方法返回的单个 int 进行比较。这是行不通的,它会将苹果与橙子进行比较,而 JUnit 会通过它的方法签名来保护你。

      您应该编写测试以匹配 maxRowAbsSum() 方法的返回类型,例如:

      @Test
      public void shouldCalculateMaxRowAbsSum() {
        int expected = 3; // example value, change to match your test scenario
        assertEquals(expected, Exercise2.maxRowAbsSum(numArray));
      }
      

      【讨论】:

      • 什么失败了,错误信息是什么? 3 的值是一个示例,调整它以匹配您的测试场景。
      • 我第一次将其更改为 23,它应该是 23。它输出所有行中的最大绝对值总计。当使用 JUnit 进行测试时,它说预期是“2”而不是“23”。该程序输出 23 所以我不明白为什么它期望 2。
      【解决方案3】:

      我修复了我的代码,但仍然使用 Karol 的示例:

      我没有将 return indexOfMaxRow 返回具有最大值的行的索引,而是将其更改为 return maxRow 这返回 23 而不是 JUnit 期望的 2。

      【讨论】:

        猜你喜欢
        • 2016-05-30
        • 2018-11-24
        • 1970-01-01
        • 2017-05-12
        • 2023-04-11
        • 2014-05-28
        • 2012-02-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多