2017-05-28 81 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

相关问题