Ander
Ander

Reputation: 513

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

I have the following classes on 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 ...

And my unit tests:

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(...) == ...

Question: How can I patch the DataObject or its contains() method to allow my test to go through?

Upvotes: 0

Views: 1995

Answers (1)

Samwise
Samwise

Reputation: 71454

Since your constructor takes a DataObject parameter, you don't even need patch, and can just pass a Mock in its place:

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(...) == ...

Upvotes: 1

Related Questions