在Python中模拟对象列表

时间:2017-08-03 10:16:27

标签: python python-2.7 testing mocking pytest

在我的FooClass我已经self.mylistMyObject组成,并且正在通过某些数据库查询创建。
到目前为止,在我的测试中,我一直在使用pytest fixture:

    @fixture
    def mock_mylist():
        foo = FooClass()
        foo.mylist = MagicMock()
        return foo

当我必须测试方法时,它工作得很好,我需要mylist只需要一些列表"。但是,其中一种方法是依赖mylist并执行一些检查,例如

for el in mylist:
    if el.MyObject.a == 1 and el.MyObject.b == 2 and...
        #compare el.MyObject.c to some external value and process...

总而言之,我需要使用模拟mylist进行测试MyObject,但我想以某种方式定义一些模拟的MyObject属性。

1 个答案:

答案 0 :(得分:0)

提前准备对象:

@fixture
def mock_mylist():
    foo = FooClass()
    foo.mylist = MagicMock()
    for el in foo.mylist:
        el.MyObject.a = 1
        el.MyObject.b = 2
        # …and…
    return foo