2017-08-25 99 views
0

我對球員類的構造函數的assertEquals()用一個HashSet

public Player(String name, String playerDescription, 
     HashSet<String> abilities) { 

      this.name = name; 
      this.playerDescription; 
      this.abilities = abilities; 
} 

創建

Player p = new Player ("Jon Snow", "Brave Swordsman", new HashSet<String>()); 

我創建了一個addAbilities()方法這個類的一個實例,添加到HashSet

public void addAbilities(String newAbility) { 
    abilities.add(newAbility); 
} 

然而,當我去測試方法(使用GET方法)

public String getAbility() { 
    String abilityString = abilities.toString(); 

    return abilityString; 
} 

我的測試:

@Test 
public void testAddAbility() { 
Player p = new Player("Jon Snow", "Brave Swordsman", new HashSet<String>()); 

    s.addAbility("Leadership"); 
    assertEquals("Leadership", s.getAbility()); 
} 

我得到測試輸出的差異。

比較失敗:預計:<[Leadership]><[[Leadership]]>

我的問題是,爲什麼會出現在輸出差異,是很好的做法,使HashSet這樣?

+1

因爲你整個集合轉換爲字符串,則應該有一個像'球員#hasAbility(字符串)'它調用的方法'能力#contains' – Rogue

+1

我可以」立即明白爲什麼輸出是錯誤的,但爲了解決其他問題,你確定你需要讓構造函數接受一個哈希集?難道你不能在構造函數中創建一個嗎? – Carcigenicate

+0

不要將參數或變量聲明爲'HashSet'。因爲實現可能會改變,所以只使用'Set' ...另外,對於預定義的功能,使用'enum's。 –

回答

4

HashSet.toString()返回一個字符串顯示內部[]元素(和它們之間,字符)。
因此,在您的斷言中,您將Leadership[Leadership]比較。

這將爲斷言是確定:

assertEquals("[Leadership]", s.getAbility()); 

但我認爲你應該改變,而檢索能力的方法。
它是一種檢索和格式化方法? 從這個意義上重命名該方法。

,否則保持Set抽象,就回到了Set,因爲它是:

public Set<String> getAbilities(){ 
    return abilities; 
} 
+0

謝謝,我現在明白了。 – Ben

2

Set toString輸出的格式是「[item1,item2,...]」。你只有一個項目,所以它是「[item1]」。

我建議你使用此法

public Set<String> getAbilities() 

或者更好的

public Set<Ability> getAbilities() 
+0

好主意。將實施。 – Ben

0

你的代碼有潛在缺陷在幾個點,第一個是

能力是一個集合,所以此getter是不正確的,因爲它返回一個字符串

public String getAbility() { 
    String abilityString = abilities.toString(); 

    return abilityString; 
} 

讓「吸」是給回一個字符串的Java JDK開發板的人可以改變,甚至沒有通知任何人...作爲一種神祕感

@test失敗....

你應該在getter和從檢查字符串值是否存在返回(一個不可修改的)收集...

Set<String> mySet = new HashSet<>(); 
mySet.add("Leader"); 
mySet.contains("Leader"); 

現在,你是什麼在未來的的toString發生的indeendent實施一個HashSet

0

我建議去掉getAbility()方法和添加:

public boolean hasAbility(String ability) { 
    return abilities.contains(ability); 
} 

用於測試加方法,你可以這樣做:

@Test 
public void testAddAbility() { 
    Player p = new Player("Jon Snow", "Brave Swordsman", new HashSet<String>()); 
    p.addAbility("Leadership"); 

    assertTrue(p.hasAbility("Leadership")); 
}