简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM