Search code examples
pythonmockingpython-mock

Mock a class imported in a different module


Let's say I have those modules:

a.py

class C:
    ...

b.py

from a import C
...
def foo():
   c = C()
   ...
...

now I want to write a test for module b

test_b.py

import unittest
import mockito

from b import foo


class TestB(unittest.TestCase):
   def test_foo():
      actual = foo()
      ...

I want "control" the behavior of foo() during the test, and I want to replace, during the test_foo() run, that when C() is created, inside foo(), it's not the "real" C class, but a mocked one, with a custom behavior How can I achieve this?


Solution

  • you can use unittest.mock.patch:

    import unittest.mock
    
    from a import C
    from b import foo
    
    class MockC:
        ...
    
    class TestB(unittest.TestCase):
       def test_foo():
            with unittest.mock.patch('a.C', new=MockC):
                actual = foo() # inside foo C will be the MockC class
                ...