在其他对象中使用的 Pytest 模拟对象的方法

Pytest mock object's method to be used within other object

我在 my_classes.py 上有以下 类:

class DataObject:
    def __init__(self):
        self.data = []

    def load(data):
        # do some really expensive stuff
        self.data = ...

    def contains(self, value):
        return value in self.data

class ObjectToBeTested:
    def __init__(self, dataObject: DataObject):
        self.dataObject = dataObject

    def method_to_be_tested(self, value):

        # do some stuff...

        # I want to patch the value returned by this call
        x = self.dataObject.contains(value)

        # so some more stuff

        return ...

我的单元测试:

from my_clases.py import ObjectToBeTested

def test_method():

  dataObject = DataObject()

  # DON'T WANT TO CALL dataObject.load(...)

  objectToBeTested = ObjectToBeTested(dataObject)
  
  assert objectToBeTested.method_to_be_tested(...) == ...

问题:如何将 DataObject 或其 contains() 方法修补为让我的测试通过?

由于您的构造函数采用 DataObject 参数,因此您甚至不需要 patch,只需传递一个 Mock 即可:

from unittest.mock import Mock

def test_method():
    mock_data_object = Mock()
    mock_data_object.contains.return_value = ...
    test_object = ObjectToBeTested(mock_data_object)
    assert test_object.method_to_be_tested(...) == ...