模拟补丁特定的类实例
如何使用patch
模拟类的特定实例?
在我的测试文件中,我有:
@classmethod
def setUpClass(cls):
cls.instance_of_my_class = myClass()
其中一个测试然后调用我希望模拟返回值的myClass
中的函数。
我可以这样做。
self.instance_of_my_class.cool_fuction = Mock(return_value=(True, True))
我希望使用补丁使用进行此操作,以便模拟不会持续到其他测试中,或以某种方式 unset 。
但是,patch
需要一个像“ package.module.class.attribute”之类的字符串,因为它的目标是这样,因此
with patch("self.instance_of_my_class") as mock:
mock.return_value.cool_fuction.return_value = (True, True)
使用Trackback
assertionError将失败放置:没有名为'self''<的模块/code>
类
with patch("functions_folder.my_script.myClass") as mock:
mock.return_value.cool_fuction.return_value = (True, True)
如果我修补了类似错误的实例的
,并且模拟
返回false
测试看起来像:
def test_foo_function(self):
result = self.instance_of_my_class.foo_function()
self.assertTrue(result[0]["confirmed"])
foo_function
cool_function
我想模拟返回(true,true)
How to mock a specific instance of a class using patch
?
In my test file I have:
@classmethod
def setUpClass(cls):
cls.instance_of_my_class = myClass()
one of the tests then calls a function in myClass
that I wish to mock the return value of.
I can do so like this.
self.instance_of_my_class.cool_fuction = Mock(return_value=(True, True))
I wish to do this using with patch
so that the mock does not persist into the other tests, or to, in some way unset the mock.
However, patch
requires a string like "package.module.Class.attribute"
as it's target so putting
with patch("self.instance_of_my_class") as mock:
mock.return_value.cool_fuction.return_value = (True, True)
fails with traceback
AssertionError: No module named 'self'
If I patch the class like
with patch("functions_folder.my_script.myClass") as mock:
mock.return_value.cool_fuction.return_value = (True, True)
the wrong instance is patched and mock.called
returns False
The test looks like:
def test_foo_function(self):
result = self.instance_of_my_class.foo_function()
self.assertTrue(result[0]["confirmed"])
and foo_function
calls on cool_function
which I want to mock return (True, True)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
感谢@johnsharpe指出了答案。
在test_myclass开始时,使用相同的setupClass与我所拥有的:
工作测试用例现在看起来像:
Thanks to @johnsharpe for pointing out the answer.
with the same setUpClass at the start of Test_myClass as I had:
working test case now looks like: