3

我有兴趣修补一个文件中由另一种方法调用的方法。示例 - original.py 文件包含 -

def A():
   a = 10
   b = 5
   return a*b;

def B():
  c = A()
  return c* 10

我想为这个文件编写单元测试,比如说叫它 test.py

import mock
import unittest

class TestOriginal(unitest.TestCase):
    def test_Original_method(self):
       with patch(''):

如何使用补丁和模拟模块来测试 original.py。我希望 A() 始终返回 MagicMock() 对象而不是整数。

4

1 回答 1

2

You simply patch out the A global in the module under test. I'd use the @patch decorator syntax here:

import mock
import unittest
import module_under_test

class TestOriginal(unitest.TestCase):
    @patch('module_under_test.A')
    def test_Original_method(self, mocked_A):
        mocked_A.return_value = 42
        result = module_under_test.B()
        mocked_A.assert_called_with()
        self.assertEqual(result, 420)

This passes in the MagicMock mock object for A() as an extra argument to the test method.

Note that we explicitly named the module here. You could also use patch.object(), just naming the attribute on the module (which are your module globals):

class TestOriginal(unitest.TestCase):
    @patch.object(module_under_test, 'A')
    def test_Original_method(self, mocked_A):
        mocked_A.return_value = 42
        result = module_under_test.B()
        mocked_A.assert_called_with()
        self.assertEqual(result, 420)

You can still use a with statement too, of course:

class TestOriginal(unitest.TestCase):
    def test_Original_method(self):
        with patch('module_under_test.A') as mocked_A:
            mocked_A.return_value = 42
            result = module_under_test.B()
            mocked_A.assert_called_with()
            self.assertEqual(result, 420)
于 2015-08-27T22:28:30.117 回答