Looks like you’re almost there! The issue is with how you’re patching the A
class in your test. When you patch a.A
, you’re mocking the entire class, not just its method_a
method. To fix this, you should patch a.A.method_a
instead. Here’s the corrected test:
pythonimport unittest
import mock
import a
class TestB(unittest.TestCase):
@mock.patch('a.A.method_a')
def test_method_b(self, mock_method_a):
mock_method_a.return_value = 'Mocked A'
b = a.B()
b.method_b()
mock_method_a.assert_called_once()
if __name__ == '__main__':
unittest.main()
This way, you’re specifically mocking the method_a
method of the A
class, and your test should now pass as expected.
المزيد من المعلومات
عند استخدام @mock.patch('a.A.method_a')
، تقوم بتجاوز السلوك الطبيعي لطريقة method_a
في فئة A
وتحل محله بقيمة مزيفة تم تعيينها باستخدام mock_method_a.return_value = 'Mocked A'
، مما يضمن أنه عندما يتم استدعاء method_a
في method_b
من فئة B
، ستعود القيمة المزيفة 'Mocked A'
بدلاً من سلوك الأصلي للطريقة.
تأكدت من ذلك باستخدام mock_method_a.assert_called_once()
، وهو يتأكد من أن الطريقة المزيفة method_a
تم استدعاؤها مرة واحدة فقط خلال تنفيذ الاختبار.