2017-05-28 85 views
-1

好了,所以可以說我們有以下簡單的類:如何測試返回自定義對象列表的getter?

public class Employees{ 


     List<Person> personsList; 
     private int numberOfEmployees; 

     public void Employees(){ 

     //constructor 

     } 

     //getters & setters 

     public List<Person> getPersons(){ 
      return personsList; 
     } 

      public void addNewEmployee(Person person){ 

     this.personsList.add(person); 

    } 

    } 

,我想測試返回Person對象的列表吸氣劑(使用的Mockito)

我做這樣的事情:

@Test 
public void getPersonsTest() throws Exception{ 
    Employees.addNewEmployee(employee); //where employee is a mocked object 

    assertEquals(Employees.getPersons(),WHAT SHOULD I PUT HERE??); 


} 

任何想法?

+2

你的getPersons()是一個無效的方法。你確定發佈的代碼? – davidxxx

+0

是我的壞。要快速修復它。 –

+1

....並以靜態的方式被調用 - 請把你的遊戲,因爲這是(是鈍的)非常草率的代碼。如果您有嚴重的問題,請發佈嚴重的* real *代碼。 –

回答

1

如果你想測試一個人可以添加到你的列表中,你可以做這樣的事情。由於所有的類都是「值類」,因此使用Mockito沒有意義。

@Test 
public void singleEmployeeAddedToList() throws Exception{ 
    Employees toTest = new Employees(); 
    Person testSubject = new Person("John", "Smith"); 
    toTest.addNewEmployee(testSubject); 

    assertEquals(Collections.singletonList(testSubject), toTest.getPersons()); 
} 

注意,在一個JUnit斷言,預期的結果是第一位的,其次是你想檢查結果。如果發現錯誤,錯誤消息在斷言失敗時沒有任何意義。

請注意,這實際上更多的是addNewEmployee的測試,而不是getPersons

相關問題