【问题标题】:Unit testing two objects which return a matrix (java)单元测试两个返回矩阵的对象(java)
【发布时间】:2022-01-01 11:47:06
【问题描述】:

我正在尝试使用两个返回二维数组/矩阵的对象创建 JUnit 测试,这是我的构造函数:

public Matrix(int[][] array) {
    this.matrix = Arrays.copyOf(array, array.length); } 

这是我的测试代码:

@Test
void addValue() {
    int[][] array = {{1, 2, 3}, {1, 2, 3}};
    int[][] newArray = {{1, 2, 3, 4}, {1, 2, 3}};

    Matrix result = new Matrix(array);
    Matrix expected = new Matrix(newArray);

    assertEquals(expected,result.addValue(0,4));

}

addValueInSpecificLine 是我创建的一个函数,在本例中,它在第 0 行添加了值 4。

这是我测试的错误:

org.opentest4j.AssertionFailedError: expected: Matrix@3c0a50da<Array{array=[[1, 2, 3, 4], [1, 2, 3]]}> but was: Matrix@646be2c3<Array{array=[[1, 2, 3, 4], [1, 2, 3]]}>
Expected :Array{array=[[1, 2, 3, 4], [1, 2, 3]]}
Actual   :Array{array=[[1, 2, 3, 4], [1, 2, 3]]}

预期与实际相同,但由于某种原因测试为假。

有什么建议吗?

【问题讨论】:

标签: java arrays matrix junit


【解决方案1】:

你应该像这样定义Matrix.equals()

public class Matrix {
    final int[][] matrix;

    public Matrix(int[][] array) {
        this.matrix = Arrays.copyOf(array, array.length);
    }

    public Matrix addValue(int row, int value) {
        int size = matrix[row].length;
        int[] newRow = Arrays.copyOf(matrix[row], size + 1);
        newRow[size] = value;
        matrix[row] = newRow;
        return this;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof Matrix m
            && Arrays.deepEquals(matrix, m.matrix);
    }
}

@Test
void addValue() {
    int[][] array = {{1, 2, 3}, {1, 2, 3}};
    int[][] newArray = {{1, 2, 3, 4}, {1, 2, 3}};

    Matrix result = new Matrix(array);
    Matrix expected = new Matrix(newArray);

    assertEquals(expected, result.addValue(0, 4));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    相关资源
    最近更新 更多