在Python中模拟构造函数助手方法

2024-10-03 19:26:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我用以下方式定义了我的构造函数。在

def __init__(self):
    //set some properties
    ...
    self.helperMethod()

def helperMethod(self):
    //Do some operation

我想对helper方法进行unittest,但是为了创建执行单元测试的对象,我需要运行__init__方法。但是,这样做会调用helper方法,这是不可取的,因为这是我需要测试的方法。在

我尝试模拟__init__方法,但收到的错误是__init__ should return None and not MagicMock。在

我还尝试用下面的方法模拟helper方法,但是我找不到一种手动恢复模拟方法的方法。MagicMock.reset_模拟()不会这样做。在

^{pr2}$

对helper方法进行单元测试的最佳方法是什么?在


Tags: 方法selfhelper定义initdef方式some
1条回答
网友
1楼 · 发布于 2024-10-03 19:26:22

您是否尝试捕获helperMethod的原始值?在

original_helperMethod = SomeClass.helperMethod
SomeClass.helperMethod = MagicMock()
x = SomeClass()
SomeClass.helperMethod = original_helperMethod

您还可以使用mock库中的^{}装饰器

^{pr2}$

相关问题 更多 >