模拟Python中被其他类使用的类

问题描述 投票:0回答:1

我正在尝试模拟一个类上的函数,该函数调用其他类中的函数,调用其他类的方法,如下所示。

class check:
    def __init__(self):
        asdad

    def b(self):
        return class_test.MyClass.a()

class MyClass():
    def a():
        return "qwertu"

我尝试使用“unittest.mock”中的 Mock 来模拟“check”类的函数“b”,并且我能够模拟它,如下所示

def test_mock_class():
    main.check.b = Mock(return_value='mocked value')
    assert main.check.b() == 'mocked value'

并且它正在按预期工作。

现在我正在尝试模拟扩展类的方法,如下所示

def test_mock_class():
    class_test.MyClass.a = Mock(return_value='mocked value')
    ob = main.check()
    assert ob.b() == 'mocked value'

但它没有按预期工作,它说“qwertu”不等于“模拟值”,但我已经模拟了 MyClass 的 a() 方法,问题是什么。

pytest python-unittest python-unittest.mock pytest-mock
1个回答
0
投票
import unittest
from unittest.mock import patch
import main  # Import the module where 'check' and 'MyClass' are defined

class TestMockClass(unittest.TestCase):

    @patch('main.MyClass.a')  # Patch 'MyClass.a' as used in the 'main' module
    def test_mock_method(self, mock_a):
        # Set the return value for the mock
        mock_a.return_value = 'mocked value'

        # Create an instance of 'check' and call method 'b'
        ob = main.check()
        result = ob.b()

        # Assert that the result is the mocked value
        self.assertEqual(result, 'mocked value')

if __name__ == '__main__':
    unittest.main()
© www.soinside.com 2019 - 2024. All rights reserved.