使用 mock 測試

參考文章: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

相關文章
相關標籤/搜索