How to mock properly classes and methods from imported modules

Keywords: python python-unittest


I'm trying to create some unitary tests for a method that needs to instantiate some objects using classes from external modules that I don't want to use, as they need arguments that I can't pass at object initialization.

For example, imagine that the code I want to test has the following structure:

from module_one import Class_1
from module_two import Class_2

class MyMainClass()
    def method_to_be_tested(self, stuff):
        var_one = Class_1(
        var_two = Class_2(
        print("The var is %s" % var_two.attribute)

stuff is a complex argument, with several attributes that I can't mock.

This is what I have tried in my test method, using patch from unittest.mock (but it didn't work):

def test_method(self, mocked_class1, mocked_class2):
    stuff = mock()
    mocked_class1.return_value = 'some_stuff'
    mock_class2 = mock()
    mock_class2.attribute = 'what_i_want_to_get'
    mocked_class2 = mock_class2

It seems that the patch or something isn't working, as it throws an error telling me that str object has no attribute data, referring to var_one when is used as an argument for Class2.

What I want is to pass any argument to Class2 and get always what I defined in mock_class2.