問題描述
假設我有這樣的課程.
class SomeProductionProcess(CustomCachedSingleTon):
@classmethod
def loaddata(cls):
"""
Uses an iterator over a large file in Production for the Data pipeline.
"""
pass
現在在測試時,我想更改 loaddata()
方法中的邏輯.這將是一個不處理大數據的簡單自定義邏輯.
Now at test time I want to change the logic inside the loaddata()
method. It would be a simple custom logic that doesn't process large data.
我們如何使用 Python Mock UnitTest 框架在測試時提供 loaddata()
的自定義實現?
How do we supply custom implementation of loaddata()
at testtime using Python Mock UnitTest framework?
推薦答案
這是一個使用mock的簡單方法
Here is a simple way to do it using mock
import mock
def new_loaddata(cls, *args, **kwargs):
# Your custom testing override
return 1
def test_SomeProductionProcess():
with mock.patch.object(SomeProductionProcess, 'loaddata', new=new_loaddata):
obj = SomeProductionProcess()
obj.loaddata() # This will call your mock method
如果可以的話,我建議使用 pytest
而不是 unittest
模塊.它使您的測試代碼更加簡潔,并減少了您使用 unittest.TestCase
樣式測試獲得的大量樣板.
I'd recommend using pytest
instead of the unittest
module if you're able. It makes your test code a lot cleaner and reduces a lot of the boilerplate you get with unittest.TestCase
-style tests.
這篇關于如何為 python 單元測試提供模擬類方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!