[英]Unit testing simple word function
我是單元測試的新手,在閱讀有關它的內容時,我對如何做感到困惑。
我有這段代碼,可以打亂輸入的單詞:
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
如何為上面的代碼編寫單元測試。 謝謝
一個簡單的檢查就是為原始單詞創建字符與頻率的哈希圖。
對於前。 如果您的單詞是“ Doppelganger”,則地圖將為
D->1
o->1
p->2
e->2
l->1
g->2
a->1
n->1
r->1
為混洗的單詞創建一個相似的映射。 兩個哈希圖應該相等。
但是,這將僅檢查混洗的單詞是否包含與原始單詞相同的字母。 您還應該通過檢查String相等性並按@Shengyuan指出的多次運行shuffle來檢查單詞是否真正被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中進行了良好的測試),我們只是關心向其發送正確的參數。
您可以通過添加條件以處理空輸入和其他邊緣情況來擴展此測試。
比較shuffle()
結果兩次,如果結果相同,則使用assertFail()
shuffle()
兩次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.