[Python] Mocking Enum using unittest.mock does not work as expected

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to Mock an enum in Python so that I can assert whether a method of the class tested calls a method on the enum.

    This does not work as expected. The method in question is never called because an identity comparison of the mock with the actual enum always fails.

    class ProcessorTest(unittest.TestCase):
    def test_do_something(self):
    # Mock library does not work with enums..
    self.mock_camera = mock.create_autospec(Camera.exit)

    self.processor.process(self.mock_camera)

    # => always leads to "failed"
    self.assertTrue(self.mock_camera.do_something.called,
    "Failed")

    class Camera(Enum):
    entrance = 1
    exit = 2

    def do_something(self):
    return True

    class Processor:
    def process(self, camera):
    # this comparison always resolves to false
    if camera is Camera.exit:
    # never reached
    camera.do_something()

    Continue reading...

Compartilhe esta Página