嘲笑,存根或任何类似用作实际执行的替代品。
嘲笑的思想是基本上在一个隔离的环境中测试的一段代码,替换依赖关系假实现。例如,在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将代码的依赖关系替换为可以配置为返回预期结果或声明某些行为的“参与者”。