本文介绍了如何在 Python 中模拟具有嵌套属性的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下代码:
class Foo:
@staticmethod
def is_room_member(invitee, msg):
return invitee in msg.frm.room.occupants
我想测试方法 is_room_member
其中 invitee
是一个字符串并且occupants
是一个字符串列表.
I want to test the method is_room_member
where invitee
is a string andoccupants
is a list of string.
如果 invitee = 'batman'
和 occupants = ['batman', 'superman']
方法 is_room_member
返回 True代码>.
If invitee = 'batman'
and occupants = ['batman', 'superman']
the method is_room_member
returns True
.
msg
是需要模拟的对象,以便我可以测试此方法.
msg
is the object which needs to be mocked so that I can test this method.
如何测试这个方法,因为它需要这个具有嵌套属性的 msg
对象?
How can I test this method, since it'll require this msg
object which has nested attributes?
我希望测试类似于:
class Testing(unittest.TestCase):
def test_is_room_member(self):
occupants = ['batman', 'superman']
# mocking
# msg = MagicMock()
# msg.frm.room.occupants = occupants
self.assertTrue(Foo.is_room_member('batman', msg))
推荐答案
您的问题已有答案:使用模拟模拟嵌套属性
import unittest
import mock
class Foo:
@staticmethod
def is_room_member(invitee, msg):
return invitee in msg.frm.room.occupants
class Testing(unittest.TestCase):
def test_is_room_member(self):
occupants = ['batman', 'superman']
# mocking
mocked_msg = mock.MagicMock()
mocked_msg.frm.room.occupants = occupants
self.assertTrue(Foo.is_room_member('batman', mocked_msg))
if __name__ == '__main__':
unittest.main()
这篇关于如何在 Python 中模拟具有嵌套属性的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!