Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用模拟autospec的Python嵌套类设计_Python_Unit Testing_Mocking - Fatal编程技术网

使用模拟autospec的Python嵌套类设计

使用模拟autospec的Python嵌套类设计,python,unit-testing,mocking,Python,Unit Testing,Mocking,我看到的是这样的类层次结构: class LevelOne(object): def __init__(self,level_two_inst): self.level_two_inst = level_two_inst self.data = self.compute_sth(level_two_inst) class LevelTwo(object): def __init__(self,level_three_inst):

我看到的是这样的类层次结构:

class LevelOne(object):
    def __init__(self,level_two_inst):
        self.level_two_inst = level_two_inst
        self.data = self.compute_sth(level_two_inst)

class LevelTwo(object):
    def __init__(self,level_three_inst):
        self.level_three_inst = level_three_inst
        self.data = self.compute_sth(level_three_inst)
我想进行单元测试
LevelOne
。由于每个级别的计算步骤都相当长,因此我想使用模拟
LevelTwo
。我还想使用
spec\u st=True
来确保属性数据是
LevelTwo
的有效属性

然而,为了实例化测试的
LevelOne
,我需要模拟
LevelTwo
LevelTwo
等等

我目前的工作重点是:

class LevelOne(object):
    def __init__(self,level_two_inst=None):
        if level_two_inst is None:
            self.data = None
            return
        self.level_two_inst = level_two_inst
        self.data = self.compute_sth(level_two_inst)
现在,当运行
LevelOne
的测试时,我可以根据自己的意愿设置
data
属性。但是,我不喜欢将
level\u two\u inst
作为可选属性,因为它确实是必需的


我不熟悉测试,尤其是使用mock。如有任何提示,我们将不胜感激

您应该能够在模拟的
LevelTwo
实例(不依赖
LevelThree
)上使用的组合,并将其传递给
LevelOne
的构造函数,以便
self.compute\u sth(LevelTwo\u inst)
正确设置
数据。“然而,要像这样使用autospec,我需要实例化LevelOne。。。“.你是说二级,对吗?你能提供一些测试和评论中的代码吗?问题到底出在哪里?我编辑了这句话,让它更清楚。假设我想实例化
LevelTwo
,将其传递给测试中的类。然后我需要一个
LevelThree
等的实例。我想一个解决方法是在
LevelThree
上模拟init方法,并将
数据设置为某个测试值。但是我不能使用
spec\u st=True
,因为
数据将不会被定义。