嘲笑,存根或任何類似用作實際執行的替代品。
嘲笑的思想是基本上在一個隔離的環境中測試的一段代碼,替換依賴關係假實現。例如,在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將代碼的依賴關係替換爲可以配置爲返回預期結果或聲明某些行爲的「參與者」。