【发布时间】:2022-08-23 02:46:15
【问题描述】:
我一直在尝试测试一个使用一些参数调用另一个函数的函数。我正在尝试模拟最新的,以便它不会实际运行,而是执行一个返回一些模拟值的模拟函数。
我所拥有的 - 简化 - 看起来像这样:
def function_to_test():
a = 2
b = 3
c = 4
results = second_function(a, b, c)
return results
然后我试图模拟的函数如下所示:
def second_function(a, b , c):
a = b + c
return a
function_to_test 和 second_function 都属于 class Example。
我正在使用unittest 进行测试,不幸的是我无法切换到 pytest,因此没有 pytest 选项有帮助。
到目前为止,我在测试中所做的是:
@patch(\'rootfolder.subfolder.filename.Example.second_function\', autospec=True)
def test_function_to_test(self, get_content_mock):
get_content_mock.return_value = mocked_second_function()
res = function_to_test()
self.assertEqual(res, 10)
如你看到的我正在尝试使用模拟函数而不是实际的second_function看起来像这样:
def mocked_second_function(a, b, c):
# using a, b, c for other actions
# for the question I will just print them but they are actually needed
print(f\"{a}, {b}, {c}\")
return 10
问题是当我设置get_content_mock.return_value = mocked_second_function().
我需要传递参数,但在我的实际问题中,这些参数是在function_to_test 处生成的所以我无法事先知道他们。
我阅读了许多相关的问题和文档,但似乎找不到可以解决我的问题的东西。任何帮助甚至不同的方法都会有所帮助。
标签: unit-testing mocking python-unittest python-unittest.mock