如何模拟子方法?
How to mock sub method?
我正在测试一个有 4 个参数的方法。我嘲笑了其中一个正在通过的参数。但是我正在测试的方法也使用了 sub 方法,我也想模拟它,因为我之前已经测试过那个特定的方法。下面是same-
的说明
hello.py中的方法如下,我正在尝试测试 -
def value_a():
return a
def abcd_foo(a,b,c,d):
another_method()
现在,在 test.py 中,我想在使用 abcd_foo(a,b,c,d)
方法时模拟 another_method()
-
@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()
.
如有任何帮助,我们将不胜感激。
如果问题仍然不清楚,请告诉我。
谢谢。
这是一个如何进行多重修补的例子
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')
我正在测试一个有 4 个参数的方法。我嘲笑了其中一个正在通过的参数。但是我正在测试的方法也使用了 sub 方法,我也想模拟它,因为我之前已经测试过那个特定的方法。下面是same-
的说明hello.py中的方法如下,我正在尝试测试 -
def value_a():
return a
def abcd_foo(a,b,c,d):
another_method()
现在,在 test.py 中,我想在使用 abcd_foo(a,b,c,d)
方法时模拟 another_method()
-
@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()
.
如有任何帮助,我们将不胜感激。
如果问题仍然不清楚,请告诉我。
谢谢。
这是一个如何进行多重修补的例子
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')