I am trying to mock a class which is instantiated in the constructor of the class I am trying to test. If I define the class I am trying to mock in the same module as the one I am trying to test, everything works fine but when they are in separate modules, I get errors.
Here's my example, taken from here (Note that in my real example, the test class is in a "tests" submodule and the other two files are in "app.src.code..." module.
What am I missing?
helper.py:
import os
class Helper:
def __init__(self, path):
self.path = path
def get_path(self):
base_path = os.getcwd()
return os.path.join(base_path, self.path)
worker.py:
from helper import Helper
class Worker:
def __init__(self):
self.helper = Helper('db')
def work(self):
path = self.helper.get_path()
print(f'Working on {path}')
return path
test_worker.py:
import unittest
from unittest.mock import patch
from worker import Worker
class WorkerTest(unittest.TestCase):
def test_patching_class(self):
with patch('helper.Helper') as MockHelper:
MockHelper.return_value.get_path.return_value = 'testing'
worker = Worker()
MockHelper.assert_called_once_with('db')
self.assertEqual(worker.work(), 'testing')
Helperobject inworker.py. So try to change yourwithstatement towith patch(worker.Helper) as MockHelper:pytest?