Pytest PropertyMock 不返回不同的属性值

问题描述 投票:0回答:1

我试图模拟对象的属性以在调用时返回不同的值。现在我有

class A:
   def __init__(self):
      self.a1 = [1, 1]
      self.a2 = [2, 2]
      self.a3 = [3, 3]
   def run(self):
      for i in self.a2:
         print(f"val in a2: {i}")

def test_A(mocker):
   myObj = A()
   myObj.a2 = mocker.PropertyMock(side_effect = [[2, 3], [3,4], [4,5]])
   myObj.run()

正在给予

TypeError: 'PropertyMock' object is not iterable

python mocking pytest
1个回答
0
投票

我发现做到这一点的方法是获取对象的类型并模拟该类型的属性。因此解决方案是

def test_A(mocker):
    myObj = A()
    type(myObj).a2 = mocker.PropertyMock(
        side_effect=iter([[2, 3], [3, 4], [4, 5]])
    )
    myObj.run()
© www.soinside.com 2019 - 2024. All rights reserved.