Junit测试void 2D阵列

问题描述:

我刚开始测试。我试图测试的方法没有返回值(void),但它在它自己的类中创建了一个静态二维数组(char [] []),所以根据我的理解,这是它的副作用。Junit测试void 2D阵列

下面是一些模拟代码:

public class MyClass{ 

    public static char[][] table; 

    public void setTable(int rows, int columns, int number){ 
     board = new char[n][m]; 
     // more code that alters the table in a specific way, 
     // depending on the 3rd parameter 
    } 

现在的测试,我的想法做类似的:

public class SetTableTest{ 

    @Test 
    public void test(){ 
     MyClass test = new MyClass(); 
     assertArrayEquals(**********, test.table); 
    } 
} 

我有2个问题:

  1. 上午我允许比较像我这样的静态变量(即,test.table)。那实际上是否会返回已完成表的“实例”?

  2. 我相当肯定没有assertArrayEquals相当于二维数组,所以我该怎么做呢?

答案:

  1. 是,静态变量将填妥的 表的情况下,假设是在setTable()结束时,你设定的 完成表到table变量。如果你不这样做,它将不会有 正确的实例。

    然而,从设计的角度来看,这将是更好的 具有的存取方法,如getTable()为完成表,如果你是在MyClass设置 它给一个变量,但是这是一个不同的问题。

  2. 要测试的2D阵列中创建,我建议建立一个代表二维数组的每一行的阵列,例如

    char[] row0 == test.table[0] 
    char[] row1 == test.table[1]. 
    

    您将需要创建这些阵列自己充满价值你预计将在从setTable()创建的表格中。然后你可以为每一行使用assertArrayEquals()。例如:

    public class SetTableTest{ 
    
        @Test 
        public void test(){ 
         MyClass test = new MyClass(); 
         test.setTable(2, 2, 5); 
         char[] row0 = {x, x} // This is whatever you would expect to be in row 0 
         char[] row1 = {x, x} // This is whatever you would expect to be in row 1 
         assertArrayEquals(row0, test.table[0]); 
         assertArrayEquals(row1, test.table[1]); 
        } 
    } 
    
+0

谢谢!说得通 – Tiberiu 2014-10-04 02:03:29

有一个assertArrayEquals()这里http://junit.sourceforge.net/javadoc/org/junit/Assert.html

,所以你可以使用它的静态导入:

import static org.junit.Assert.assertArrayEquals; 

它,但是,只有“浅”阵列等于,所以你需要实现逻辑本身。另外请确保,您在声明之前致电setTable()。这里是东西:

import static org.junit.Assert.assertArrayEquals; 

public class SetTableTest{ 

    @Test 
    public void test() { 
     MyClass test = new MyClass(); 
     int foo = 42; 
     int bar = 42; 
     int baz = 42; 
     test.setTable(foo, bar, baz) 
     for (char[] innerArray : test.table) { 
      assertArrayEquals(*****, innerArray); 
     } 
    } 
}