2014-10-04 74 views
1

我剛開始測試。我試圖測試的方法沒有返回值(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

答案:

  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

2

有一個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); 
     } 
    } 
}