确实是!
如果您只需要在步骤期间模拟某些内容,那么您可以使用mock.patch
.
# features/steps/step_submit_form.py
from mock import patch
@when(u'I submitted checkout form')
def submit_checkout_form(context):
with patch('payment.gateway.pay', return_value={'success': True}, spec=True):
form.submit(fake_form_data)
如果你需要为每个场景模拟一些东西,你可以在你的 中这样做
environment.py
,使用生命周期函数:
# features/environment.py
from mock import Mock, patch
def before_scenario(context, scenario):
mock_payment_gateway = Mock()
mock_payment_gateway.pay.return_value = {'success': True}
patcher = patch('payment.gateway', mock_payment_gateway)
patcher.start()
context.payment_patcher = patcher
def after_scenario(context, scenario):
context.payment_patcher.stop()
如果您只想针对特定场景模拟它,您可以创建一个特殊的步骤来设置模拟,然后在生命周期函数中拆除:
# features/steps/step_submit_form.py
from behave import given, when, then
from mock import patch, Mock
@given(u'the payment is successful')
def successful_payment_gateway(context):
mock_payment_gateway = Mock()
mock_payment_gateway.pay.return_value = {'success': True}
patcher = patch('payment.gateway', mock_payment_gateway)
patcher.start()
context.patchers.append(patcher)
@when(u'I submitted checkout form')
def submit_checkout_form(context):
form.submit(fake_form_data, payment.gateway)
@then(u'I see my order successfully created')
def inspect_order_page(context):
check_product()
在每个场景之后去掉补丁environment.py
:
# features/environment.py
def before_scenario(context, scenario):
context.patchers = []
def after_scenario(context, scenario):
for patcher in context.patchers:
patcher.stop()