Python return fixture 而不是调用导入函数

Python return fixture instead of calling imported function

我想模拟一个导入到测试中的函数 class。在测试期间调用此函数时,我只想返回一个夹具。但在我的设置中,MyClass 中实际导入的函数仍然被调用,而不是仅仅传递 'mocked value' 作为此调用的结果。我该如何解决这个问题?

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

您的代码更正

  1. get_sth_test.py

删除 fixture 装饰器 @pytest.fixture 因为您只是将它用作普通函数。

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

将补丁替换为

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

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

解决这些文件后,它对我有效。我在 test_MyClass 中添加了 print(instance.sth),它正确显示了 mocked value