Search code examples
pythonmockingpytestfixtures

Python return fixture instead of calling imported function


I want to mock a function imported to the tested class. When this function is called during testing I just want a fixture to be returned. But in my setup, the actual imported function in MyClass is still called instead of just passing 'mocked value' as a result of this call. How do I fix this?

MyClass.py
    from api.methods import get_sth
    class MyClass:
        def __init__(self):
            self.sth = get_sth()
    

get_sth_test.py
    @pytest.fixture
    get_sth_mock_test():
        return 'mocked value'


MyClass_test.py
    from get_sth_test import get_sth_mock_test
    from MyClass import MyClass
    @mock.patch('MyClass.get_sth', return_value=get_sth_mock_test)
    def test_MyClass(get_sth_mock):
        instance = MyClass()
    

Solution

  • Corrections on your code

    1. get_sth_test.py

    Remove fixture decorator @pytest.fixture because you are just using it as an ordinary function.

    def get_sth_mock_test():
        return 'mocked value'
    
    1. MyClass_test.py

    Replace the patching to

    @mock.patch('MyClass.get_sth', return_value=get_sth_mock_test())  # Notice the suffix "()" to invoke the function and return its value.
    

    or

    @mock.patch('MyClass.get_sth', side_effect=get_sth_mock_test)
    

    It worked on my side after resolving this files. I added print(instance.sth) in the test_MyClass and it correctly displayed mocked value.