参考文章:https://semaphoreci.com/community/tutorials/getting-started-with-mocking-in-pythonhtml
What are the benefits of mocking? Increased speed — Tests that run quickly are extremely beneficial. E.g. if you have a very resource intensive function, a mock of that function would cut down on unnecessary resource usage during testing, therefore reducing test run time. Avoiding undesired side effects during testing — If you are testing a function which makes calls to an external API, you may not want to make an actual API call every time you run your tests. You'd have to change your code every time that API changes, or there may be some rate limits, but mocking helps you avoid that.
上文中测试 requests 也使用了 patch,但我如今是使用 httpmock,感受更加方便。python
疑问:既然我 mock 了代码的返回值,那么我怎么测试这部分代码?redis
1. 这部分代码是不须要测试的api
好比调用别人的 api 接口,这部分代码时不归本身管,不属于这个单元测试。less
2. 这部分代码须要测试ide
单独为这部分写一个单元测试,在这里进行实际测试。在其余测试中,须要引用这个的地方,使用 mock单元测试
疑问:mock redis 这样的系统组件有没有必要?是否给它一个单独的测试 redis db 会更好?测试
坏处:这样增长了代码,以后写单元测试还要修改这个 mock 部分的代码。随着代码功能的增长,最后你可能要实现整个 redis 的 api。ui
My initial belief was correct: It’s not a good practice to mock out major subsystems for testing. If it’s possible to do so, it’s less work and provides more effective testing to hook your tests up to real subsystems, and not to mocks of the subsystems. You should mock a subsystem if and only if it’s prohibitive to test against the real thing. -- from Replacing Redis with a Python Mockcode