模拟在不同模块中导入的 class
Mock a class imported in a different module
假设我有这些模块:
a.py
class C:
...
b.py
from a import C
...
def foo():
c = C()
...
...
现在我想为模块 b
编写一个测试
test_b.py
import unittest
import mockito
from b import foo
class TestB(unittest.TestCase):
def test_foo():
actual = foo()
...
我想在测试期间“控制”foo()
的行为,并且我想在 test_foo()
运行 期间替换创建 C()
的行为,在 foo()
中,它不是“真实的”C
class,而是一个模拟的,具有自定义行为
我怎样才能做到这一点?
你必须 import b
到你的 test_b.py
,然后分配给 b.C
你的模拟 class,像这样:
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
您可以使用 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
...
假设我有这些模块:
a.py
class C:
...
b.py
from a import C
...
def foo():
c = C()
...
...
现在我想为模块 b
test_b.py
import unittest
import mockito
from b import foo
class TestB(unittest.TestCase):
def test_foo():
actual = foo()
...
我想在测试期间“控制”foo()
的行为,并且我想在 test_foo()
运行 期间替换创建 C()
的行为,在 foo()
中,它不是“真实的”C
class,而是一个模拟的,具有自定义行为
我怎样才能做到这一点?
你必须 import b
到你的 test_b.py
,然后分配给 b.C
你的模拟 class,像这样:
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
您可以使用 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
...