如何在Python中使用嵌套属性模拟对象?

时间:2018-06-05 00:13:14

标签: python python-3.x unit-testing mocking

我想模仿方法is_room_member,其中invitee是一个字符串 occupants是字符串列表。

如果invitee = 'batman'occupants = ['batman', 'superman']方法is_room_member返回True

class Foo:
    @staticmethod
    def is_room_member(invitee, msg):
        return invitee in msg.frm.room.occupants

msg是需要模拟的对象,以便我可以测试此方法。

如何测试此方法,因为它需要这个具有嵌套属性的msg对象?

我希望测试类似于:

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))

2 个答案:

答案 0 :(得分:1)

您的问题现有答案: Mocking nested properties with mock

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()

答案 1 :(得分:0)

由于MagicMock如此神奇......它正是你所写的。

class Testing(unittest.TestCase):
    def test_is_room_member(self):
    occupants = ['batman', 'superman']
    msg = MagicMock()
    msg.frm.room.occupants = occupants
    print(msg.frm.room.occupants) # >>> ['batman', 'superman']
    self.assertTrue(Foo.is_room_member('batman', msg))

来自unittest docs

  

Mock和MagicMock对象在您访问它们时会创建所有属性和方法,并存储它们的使用方式的详细信息。

除非你另有说法,否则一切都会返回MagicMock!