【问题标题】:Mocking list of objects in PythonPython中的模拟对象列表
【发布时间】:2017-08-03 10:16:26
【问题描述】:

在我的FooClass 中,我有self.mylist,它由MyObjects 组成,并且是从一些数据库查询中创建的。
到目前为止,在我的测试中,我一直在使用 pytest 固定装置:

    @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...

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

【问题讨论】:

    标签: python python-2.7 testing mocking pytest


    【解决方案1】:

    提前准备物品:

    @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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 2020-12-08
      • 1970-01-01
      • 2022-10-17
      相关资源
      最近更新 更多