2011-03-26 95 views
1

我是新來的單元測試和閱讀它的時候,我弄不清如何做到這一點。單元測試簡單的文字功能

我有這個代碼進入洗牌一句話:

public static void shuffle(String word) { 

    // Store string into array 
     ArrayList<Character> wordShuffled = new ArrayList<Character>(); 
     // loop the index of the string 
     for (int i = 0; i < wordE.length(); i++) { 
      wordShuffled.add(word.charAt(i));// add the word 
     } 
     Collections.shuffle(wordShuffled);// shuffle the word 

我如何編寫單元測試上面的代碼。由於

+0

@CarlosZ提出了一個有效的觀點。爲什麼測試Collections.shuffle(),因爲我們知道它工作正常。在那種情況下,爲什麼測試這個功能呢?for循環也可以用標準API來替換,以將原始字符串轉換爲字符列表,從而將您的代碼減少到一兩行。 – Rahul 2011-03-26 04:20:57

回答

0

明顯的通行證測試:

安排:創建一個已知的字。

:呼叫洗牌。

斷言:檢查結果是原詞的排列。

然後尋找故障點或邊界案件作進一步檢查。

0

一對夫婦的,使這段代碼難以測試的問題是:

  1. 你的功能洗牌聲明爲static
  2. 的函數調用Collections.shuffle,使得它真的很難嘲笑

這裏有一些建議,你如何可以測試這種方法,儘管他們需要一些改變你的設計:

public class WordUtil { 
    public void shuffle(String word) { 

     // Store string into array 
     // -> It is better to code to the interface, eg, List, Set, Map 
     // than to the implementation, eg. ArrayList, LinkedList, HashMap, etc. 
     List<Character> wordShuffled = new ArrayList<Character>(); 
     // loop the index of the string 
     for (int i = 0; i < wordE.length(); i++) { 
      wordShuffled.add(word.charAt(i));// add the word 
     } 
     Collections.shuffle(wordShuffled);// shuffle the word 
    } 
    // we are making this method visible only for testing purposes but 
    // shouldn't be regarded as public API 
    void shuffle(Collection c) { 
     Collections.shuffle(c); 
    } 
} 

public class WordUtilTest { 
    private boolean shuffleForCollectionWasCalled; 
    private Collection collectionForShuffle; 

    public void testShuffle() throws Exception { 
     WordUtil util = new WordUtil_ForTest(); 
     String word = "some word"; 

     util.shuffle(word); 

     assertTrue(shuffleForCollectionWasCalled); 
     List<Character> expected = new ArrayList<Character>(); 
     for (int i = 0; i < word.length; i++) { 
      expected.add(word.charAt(i); 
     } 
     assertEquals(expected, collectionForShuffle); 
    } 

    private static class WordUtil_ForTest extends WordUtil { 

     @Override 
     void shuffle(Collection c) { 
      shuffleForCollectionWasCalled = true; 
      collectionForShuffle = c; 
     } 
    } 
} 

雖然這似乎有點令人費解,我們需要引入void shuffle(Collection c),因爲它使我們能夠控制的Collections.shuffle使其確定性的行爲,我們在WordUtil_ForTest實現很簡單,因爲我們沒有測試Collections.shuffle如何完成其​​工作(這應該在JDK中得到很好的測試),我們只關心我們發送正確的參數給它。

可以通過添加條件處理空輸入和另一個邊緣延伸的情況下該測試。

1

一個簡單的檢查是創建角色的一個HashMap與頻率爲原來的字。

例如,如果您的單詞是「Doppelganger」,地圖將爲

D->1 
o->1 
p->2 
e->2 
l->1 
g->2 
a->1 
n->1 
r->1 

爲混洗詞創建類似地圖。兩個hashmaps應該是平等的。

但是,這隻會檢查混洗字是否包含與原始單詞相同的字母。 @Shengyuan指出,你還應該通過檢查字符串相等性並多次運行洗牌來檢查該字是否實際上被洗牌。

0

比較結果shuffle()兩次,assertFail()如果結果相同。