java实现矩阵乘法的unit test
时间: 2024-05-04 20:15:13 浏览: 12
以下是一个简单的Java实现矩阵乘法的unit test:
```
import org.junit.Test;
import static org.junit.Assert.*;
public class MatrixMultiplicationTest {
@Test
public void testMatrixMultiplication() {
int[][] a = {{1, 2, 3}, {4, 5, 6}};
int[][] b = {{7, 8}, {9, 10}, {11, 12}};
int[][] expected = {{58, 64}, {139, 154}};
int[][] result = MatrixMultiplication.multiply(a, b);
assertArrayEquals(expected, result);
}
}
```
在这个测试中,我们定义了两个矩阵a和b,它们分别是2x3和3x2的矩阵。我们期望的结果是一个2x2的矩阵,我们使用一个名为"expected"的数组来存储这个结果。我们使用MatrixMultiplication.multiply()方法来计算实际结果,并使用JUnit的assertArrayEquals()方法来比较期望和实际结果。如果它们不相等,测试将失败。
相关问题
java实现矩阵逆的unit test
以下是一个Java实现矩阵逆的单元测试示例:
```
import org.junit.Test;
import static org.junit.Assert.*;
public class MatrixInverseTest {
@Test
public void testInverse() {
double[][] matrix = {{1, 2}, {3, 4}};
double[][] expectedInverse = {{-2, 1}, {1.5, -0.5}};
double[][] actualInverse = MatrixInverse.inverse(matrix);
assertArrayEquals(expectedInverse, actualInverse);
}
@Test
public void testSingularMatrix() {
double[][] matrix = {{1, 2}, {2, 4}};
assertNull(MatrixInverse.inverse(matrix));
}
@Test
public void testNonSquareMatrix() {
double[][] matrix = {{1, 2, 3}, {4, 5, 6}};
assertNull(MatrixInverse.inverse(matrix));
}
}
```
这个测试类使用JUnit测试框架,测试了三个场景:
- 正常情况下,矩阵可以逆转,并且预期逆矩阵与实际逆矩阵相等。
- 矩阵是奇异的,即没有逆矩阵,实际逆矩阵应该为null。
- 矩阵不是方阵,因此没有逆矩阵,实际逆矩阵应该为null。
如果所有测试用例都通过,则可以确认矩阵逆的实现是正确的。
java实现矩阵加法的unit test
以下是一个Java实现矩阵加法的单元测试示例:
```java
import org.junit.Test;
import static org.junit.Assert.*;
public class MatrixAdditionTest {
@Test
public void testMatrixAddition() {
int[][] matrixA = {{1, 2}, {3, 4}};
int[][] matrixB = {{5, 6}, {7, 8}};
int[][] expected = {{6, 8}, {10, 12}};
MatrixAddition matrixAddition = new MatrixAddition();
int[][] result = matrixAddition.add(matrixA, matrixB);
assertArrayEquals(expected, result);
}
}
```
在这个测试中,我们创建了两个2x2的矩阵matrixA和matrixB,然后将它们传递给MatrixAddition类中的add()方法,该方法将这两个矩阵相加。我们期望得到的结果是一个2x2的矩阵,其中每个元素都是对应位置上两个矩阵元素的和。
我们使用JUnit的assertArrayEquals()方法来比较预期的结果和实际结果。如果它们不相等,测试将失败并抛出异常。如果测试通过,您将看到一个绿色的测试通过标记。