您可以使用patch decorator,然后对模拟对象调用assert_called_with,如下所示:
如果您有这种结构:example.py
tests.py
lib/__init__.py
lib/event.py
而example.py的内容是:import lib
METADATA = 'metadata_example'
class Monolith(object):
def foo(self, raw_event):
action = 'action_example' # ... Parse Event
# Middle of function
lib.event.Event(METADATA, action)
# Continue on to use the build event.
而lib/event.py的内容是:class Event(object):
def __init__(self, metadata, action):
pass
tests.py的代码应该如下:import mock
import unittest
from lib.event import Event
from example import Monolith
class TestExample(unittest.TestCase):
@mock.patch('lib.event.Event')
def test_example1(self, event_mocked):
# Setup
m = Monolith()
# Exercise
m.foo('raw_event')
# Verify
event_mocked.assert_called_with('metadata_example', 'action_example')