2017-08-02 74 views
0

我想测试一个HTTP服务器功能,这是我第一次获得接触到的嘲笑,存根和假货的概念。我读这本书,它说,嘲讽是描述一个复杂的对象的状态在某一个时刻,就像一个快照,测试的对象,因为它实际上是真实的。对?我明白这一点。我不明白的是编写单元测试以及我们在模拟对象中完全描述的某些情况的断言。如果我们设置的参数的期望和嘲讽的对象上的返回值,而我们测试的精确值,测试将永远传递。请纠正我。我知道我在这里失去了一些东西。单元测试究竟在做什么?

回答

0

嘲笑,存根或任何类似用作实际执行的替代品。

嘲笑的思想是基本上在一个隔离的环境中测试的一段代码,替换依赖关系假实现。例如,在Java中,假设我们要测试的PersonService#保存方法:

class PersonService { 

    PersonDAO personDAO; 

    // Set when the person was created and then save to DB 
    public void save(Person person) { 
     person.setCreationDate(new Date()); 
     personDAO.save(person); 
    } 
} 

一个很好的形式给出创造这样一个单元测试:

class PersonServiceTest { 

    // Class under test 
    PersonService personService; 

    // Mock 
    PersonDAO personDAOMock; 

    // Mocking the dependencies of personService. 
    // In this case, we mock the PersonDAO. Doing this 
    // we don't need the DB to test the code. 
    // We assume that personDAO will give us an expected result 
    // for each test. 
    public void setup() { 
     personService.setPersonDao(personDAOMock) 
    } 

    // This test will guarantee that the creationDate is defined  
    public void saveShouldDefineTheCreationDate() {   
     // Given a person 
     Person person = new Person(); 
     person.setCreationDate(null); 
     // When the save method is called 
     personService.save(person); 
     // Then the creation date should be present 
     assert person.getCreationDate() != null; 
    } 
} 

换句话说,你应该使用Mock将代码的依赖关系替换为可以配置为返回预期结果或声明某些行为的“参与者”。