問題描述
假設(shè)我有這樣的課程.
class SomeProductionProcess(CustomCachedSingleTon):
@classmethod
def loaddata(cls):
"""
Uses an iterator over a large file in Production for the Data pipeline.
"""
pass
現(xiàn)在在測(cè)試時(shí),我想更改 loaddata()
方法中的邏輯.這將是一個(gè)不處理大數(shù)據(jù)的簡(jiǎn)單自定義邏輯.
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.
我們?nèi)绾问褂?Python Mock UnitTest 框架在測(cè)試時(shí)提供 loaddata()
的自定義實(shí)現(xiàn)?
How do we supply custom implementation of loaddata()
at testtime using Python Mock UnitTest framework?
推薦答案
這是一個(gè)使用mock的簡(jiǎn)單方法
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
模塊.它使您的測(cè)試代碼更加簡(jiǎn)潔,并減少了您使用 unittest.TestCase
樣式測(cè)試獲得的大量樣板.
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.
這篇關(guān)于如何為 python 單元測(cè)試提供模擬類方法?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!