6

Consider the following code:

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

I want to test the method is_room_member where invitee is a string and occupants is a list of string.

If invitee = 'batman' and occupants = ['batman', 'superman'] the method is_room_member returns True.

msg is the object which needs to be mocked so that I can test this method.

How can I test this method, since it'll require this msg object which has nested attributes?

I want the test to be something like:

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 Answers 2

9

There is an existing answer for your question: 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()
Sign up to request clarification or add additional context in comments.

Comments

0

Since MagicMock is so magical...it is exactly what you wrote.

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

From the unittest docs:

Mock and MagicMock objects create all attributes and methods as you access them and store details of how they have been used.

Unless you say otherwise, everything returns a MagicMock!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.