如何编写JUnit测试?

时间:2017-06-05 00:44:31

标签: 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));

    // 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.
}

1 个答案:

答案 0 :(得分:0)

首先,您要创建要测试的类。

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());
    }
}

最后查看this question关于如何从命令行运行测试用例的答案。