什么是单元测试中的嘲弄?

时间:2017-08-02 16:20:31

标签: unit-testing testing mocking

我正在尝试测试http服务器功能,这是我第一次接触到模拟,存根和假货的概念。我正在读这本书,它说模拟是在特定时刻描述复杂对象的状态,如快照,并测试对象,因为它实际上是真实的。对?我理解这一点。我不明白的是编写单元测试和断言我们在mock对象中完全描述的某些情况的重点是什么。如果我们在模拟对象上设置参数和返回值的期望值,并且我们测试那些确切的值,那么测试将始终通过。请指正。我知道我在这里遗漏了一些东西。

1 个答案:

答案 0 :(得分:0)

Mocks,Stubs或类似的东西可以替代实际的实现。

模拟的想法基本上是在隔离环境中测试一段代码,用依赖项替换虚假实现。例如,在Java中,假设我们要测试PersonService#save方法:

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将代码的依赖项替换为可以配置为返回预期结果或断言某些行为的“actor”。

相关问题