假设我有这样的课程.
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模板网!
Python 3 浮点小数点/精度Python 3 Float Decimal Points/Precision(Python 3 浮点小数点/精度)
将浮点数转换为美元和美分Converting Float to Dollars and Cents(将浮点数转换为美元和美分)
numpy 或 scipy 有哪些可能的计算可以返回 NaN?What are some possible calculations with numpy or scipy that can return a NaN?(numpy 或 scipy 有哪些可能的计算可以返回 NaN?)
Python浮动比率Python float to ratio(Python浮动比率)
如何在 Python 中管理大量数字的除法?How to manage division of huge numbers in Python?(如何在 Python 中管理大量数字的除法?)
pandas 和 numpy 的意思不同mean from pandas and numpy differ(pandas 和 numpy 的意思不同)