如何模拟子方法?

时间:2018-01-30 10:49:33

标签: python python-3.x unit-testing mocking python-unittest

我正在测试一个有4个参数的方法。对于其中一个过时的游行,我已经嘲笑了。但我正在测试的方法也使用sub方法,我也想模拟,因为我之前测试过那个特定的方法。下面是相同的插图 -

hello.py 中的方法如下我正试图测试 -

def value_a():
    return a

def abcd_foo(a,b,c,d):
    another_method()

现在,在 test.py 中,我想在使用another_method()方法时模拟abcd_foo(a,b,c,d) -

@patch('hello.value_a')
def test_result(self, mock_result_a):         
    mock_result_a.return_value = 'mocking successful of a'
    abcd_foo(mock_result_a.return_value,b,c,d)

现在,在使用abcd_foo时,它还使用了另一种方法another_mothod()。那么,如何模仿another_method()

任何帮助都将不胜感激。

如果问题仍然没有清除,请告诉我。

感谢。

1 个答案:

答案 0 :(得分:1)

以下是如何进行多次修补的示例

    class TestABCDFoo(unittest.TestCase):

        @mock.patch('hello.value_a', return_value='mocking_va')
        @mock.patch('hello.another_method', return_value='mocking_another')
        def test_result(self, mock_value_a, mock_another_method):
            """
            The return_value better to be defined outside the test function with multiple patch
            """
            a = value_a()
            self.assertEqual(a, 'mocking_va')
            result = abcd_foo(a, 'b', 'c', 'd')
            self.assertEqual(result, 'mocking_another')