使用 mock 测试

参考文章:https://semaphoreci.com/community/tutorials/getting-started-with-mocking-in-python

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,感觉更加方便。

 

疑问:既然我 mock 了代码的返回值,那么我怎么测试这部分代码?

1. 这部分代码是不需要测试的

比如调用别人的 api 接口,这部分代码时不归自己管,不属于这个单元测试。

2. 这部分代码需要测试

单独为这部分写一个单元测试,在这里进行实际测试。在其他测试中,需要引用这个的地方,使用 mock

 

疑问:mock redis 这样的系统组件有没有必要?是否给它一个单独的测试 redis db 会更好?

坏处:这样增加了代码,之后写单元测试还要修改这个 mock 部分的代码。随着代码功能的增加,最后你可能要实现整个 redis 的 api。

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 Mock

转载于:https://www.cnblogs.com/jay54520/p/6530676.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值