2017-08-02 72 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將代碼的依賴關係替換爲可以配置爲返回預期結果或聲明某些行爲的「參與者」。