2x2矩阵行列式计算代码JUnit测试失败,请求排查问题
问题分析与解决
核心问题:方法名不匹配
Matrix类中定义的行列式计算方法名为determinant,但JUnit测试代码里调用的是Matrix.det2(),这会引发两种异常情况:- 若项目中不存在
det2方法,会直接编译失败; - 若存在其他
det2方法,调用的就不是你编写的正确逻辑,自然会出现预期值与实际结果不符的错误(比如你遇到的expected<3> but was <9>)。
- 若项目中不存在
修复步骤:
将JUnit测试里的Matrix.det2()全部替换为Matrix.determinant(),修改后的测试代码如下:
package maths; import org.junit.Test; import static org.junit.Assert.assertEquals; public class SolutionTest { @Test public void detTest() { int[][] matrix1 = { { 1, 2 }, { 3, 4 } }; int[][] matrix2 = { { 5, 6 }, { 7, 8 } }; int[][] matrix3 = { { -2, 3 }, { 1, -3 } }; assertEquals(Matrix.determinant(matrix1), -2); assertEquals(Matrix.determinant(matrix2), -2); assertEquals(Matrix.determinant(matrix3), 9); } }
- 逻辑验证:
你编写的determinant方法逻辑完全正确,符合2x2矩阵行列式的计算公式ad - bc,手动验证的预期值也无误,修正方法名后测试即可正常通过。
内容的提问来源于stack exchange,提问作者cnd
相关产品推荐
相关产品推荐

