Adrian.C
Adrian.C

Reputation: 11

How do I mock a class from a different module in Python?

In Python I have 3 files in the same folder: file1.py, file2.py and test.py

file1.py contains a simple class definition

class MyClass:
    def __init__(self, a, b):
        self.a = a
        self.b = b
        print(f"a={a} and b={b}")

file2.py instantiate previous class

from file1 import MyClass

def instantiate_class():
    o = MyClass(1,2)

In test.py I'm trying to mock the file1.MyClass from instantiate_class() function

from unittest.mock import patch
from file2 import instantiate_class

with patch("file1.MyClass") as mock_check:
    instantiate_class()
    print(mock_check.call_args)

Problem is that class MyClass from file2.py is not mocked as the print from the MyClass constructor is called.

Only solution I found to solve this is to change file2.py with:

import file1 

def instantiate_class():
    o = file1.MyClass(1,2)

Is there a solution to obtain mocking that does not involve changing file1.py and file2.py? I only want to change the test.py file (writing unit tests for existing classes).

Upvotes: 0

Views: 45

Answers (1)

hstk
hstk

Reputation: 169

I need to mock the file2.mock instead of file1.mock. Like below:

from unittest.mock import patch
from file2 import instantiate_class

with patch("file2.MyClass") as mock_check:
    instantiate_class()
    print(mock_check.call_args)

reference

where-to-patch

Upvotes: 1

Related Questions