[英]unittest mock how to mock a method being called
I want to test that method a
calls method b
.我想测试该方法
a
调用方法b
。 These methods are in separate files, and are not a part of class object.这些方法位于单独的文件中,不是类对象的一部分。
# file_a.py
from file_b import b
def a():
b()
# file_b.py
def b():
test
import unittest
from unittest import mock
from file_a import a
class MyTestCase(unittest.TestCase):
@mock.patch('file_b.b')
def test_b_called(self, mock):
a()
mock.assert_called()
if __name__ == "__main__":
unittest.main()
This fails with AssertionError: Expected 'b' to have been called.
这失败了
AssertionError: Expected 'b' to have been called.
Is there a right way to do this?有没有正确的方法来做到这一点?
When you import a function into the current namespace, like in your example, the function will need to be patched in that namespace.当您将函数导入当前命名空间时,就像在您的示例中一样,需要在该命名空间中修补该函数。 In your case, you need:
在您的情况下,您需要:
@mock.patch('file_a.b')
You would patch file_b.b
if you had done the import and use like this:如果您已经完成导入和使用,您将修补
file_b.b
:
import file_b
def a():
file_b.b()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.