作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
考虑以下代码。我想模拟 self.get_value
,它在 foo.verify_client()
import unittest
import mock
def mock_get_value(self, value):
return 'client'
class Foo:
def __init__(self):
pass
def get_value(self, value):
return value
def verify_client(self):
client = self.get_value('client')
return client == 'client'
class testFoo(unittest.TestCase):
@mock.patch('self.get_value', side_effect = mock_get_value, autospec = True)
def test_verify_client(self):
foo = Foo()
result = foo.verify_client()
self.assertTrue(result)
if __name__ == "__main__":
unittest.main()
但是我失败了,错误如下。
E
======================================================================
ERROR: test_verify_client (__main__.testFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1297, in patched
arg = patching.__enter__()
File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1353, in __enter__
self.target = self.getter()
File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1523, in <lambda>
getter = lambda: _importer(target)
File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1206, in _importer
thing = __import__(import_path)
ImportError: No module named self
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
我该怎么做?
最佳答案
我想通了。改变这一行
@mock.patch('self.get_value', side_effect = mock_get_value, autospec = True)
到
@mock.patch('test.Foo.get_value', mock_get_value)
成功了。
注意打补丁函数的格式应该是module_name + class_name + method_name
关于python - 如何在 python 中模拟 self ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39698094/
我是一名优秀的程序员,十分优秀!