2017-06-05 256 views
-3

我有一个assingment,要求我测试一个矩阵是否满足我已经完成的某个要求,然后在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. 
} 
+0

你看过JUnit网站上JUnit测试的例子吗? –

+0

是的,我尝试过但我找不到有用的东西 – none

+1

一般来说,你会创建另一个类(例如'TestMagicSquare'),并使用注解来标记将调用测试的方法(例如'testValidSquare()'和' testInvalidSquare()'),编写适当的方法,然后用JUnit系统调用它。如果您使用的是Eclipse或其他IDE,则运行测试的过程会稍微简化一些。 – KevinO

回答

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