Java 如何编写JUnit测试?
我有一个任务,要求我测试矩阵是否满足特定的要求,我已经完成了,然后在JUnit测试中测试它,我不知道如何测试。我已经为JUnit测试创建了文件夹,但我不知道如何编写测试。到目前为止,我在主课上做了测试Java 如何编写JUnit测试?,java,junit,Java,Junit,我有一个任务,要求我测试矩阵是否满足特定的要求,我已经完成了,然后在JUnit测试中测试它,我不知道如何测试。我已经为JUnit测试创建了文件夹,但我不知道如何编写测试。到目前为止,我在主课上做了测试 public static void main(String[] args) { int matrix[][] = {{2,7,6},{9,5,1},{4,3,8}}; System.out.println(isMagicSquare(matrix)); // chan
public static void main(String[] args) {
int matrix[][] = {{2,7,6},{9,5,1},{4,3,8}};
System.out.println(isMagicSquare(matrix));
// changing one element
matrix[0][2] = 5;
System.out.println(isMagicSquare(matrix));
}
public static boolean isMagicSquare(int[][] matrix) {
// actual code omitted for the sake of simplicity.
}
首先,创建要测试的类
public class MagicSquare
{
private int[][] matrix;
public MagicSquare(int[][] matrix)
{
this.matrix = matrix;
}
public boolean isValid()
{
// validation logic
}
}
然后创建测试类
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class MagicSquareTest
{
@Test
public void testMagicSquare1()
{
int[][] matrix = { { 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 } };
MagicSquare square = new MagicSquare(matrix);
// this is a valid magic square
assertTrue(square.isValid());
}
@Test
public void testMagicSquare2()
{
int[][] matrix = { { 2, 7, 5 }, { 9, 5, 1 }, { 4, 3, 8 } };
MagicSquare square = new MagicSquare(matrix);
// this is an invalid magic square
assertFalse(square.isValid());
}
}
终于可以从命令行看到关于如何运行测试用例的答案了。你看过JUnit网站上的JUnit测试示例吗?是的,我试过了,但找不到有用的东西。通常,你会创建另一个类(例如,
TestMagicSquare
),并使用注释来标记将调用测试的方法(例如,testValidSquare()
和testInvalidSquare()
),适当地编写方法,然后在JUnit系统中调用它。如果您使用的是Eclipse或其他IDE,则运行测试的过程会稍微简化。