0

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?

Vito De Tullio
  • 2,332
  • 3
  • 33
  • 52

2 Answers2

0

You have to import b into your test_b.py, and then assign to b.C your mocked class, like this:

import unittest

import b

class TestB(unittest.TestCase):
    class MockC:
        def talk(self):
            return 'Mocked C'

    def test_foo(self):
        b.C = self.MockC
        talk = b.foo()  # returns C().talk()
        assert talk == 'Mocked C'  # ok
crissal
  • 2,547
  • 7
  • 25
0

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
            ...
Vito De Tullio
  • 2,332
  • 3
  • 33
  • 52