一對夫婦的,使這段代碼難以測試的問題是:
- 你的功能洗牌聲明爲static
- 的函數調用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中得到很好的測試),我們只關心我們發送正確的參數給它。
可以通過添加條件處理空輸入和另一個邊緣延伸的情況下該測試。
@CarlosZ提出了一個有效的觀點。爲什麼測試Collections.shuffle(),因爲我們知道它工作正常。在那種情況下,爲什麼測試這個功能呢?for循環也可以用標準API來替換,以將原始字符串轉換爲字符列表,從而將您的代碼減少到一兩行。 – Rahul 2011-03-26 04:20:57