我看过很多关于使用模拟进行单元测试的文章。
我有一个简单的结帐表单,可将卡详细信息提交到支付网关。是否可以模拟 Behave tests 中的支付网关响应?
@then(u'I submitted checkout form')
def submit_checkout_form(context):
"Mock your response Do not send/post request to payment gateway, but create order"
@then(u'I see my order successfully created')
def inspect_order_page(context):
"Thank you page: check product & price"
我想知道,是否可以在行为测试中进行模拟?
最佳答案
确实是这样!
如果您只需要在该步骤期间模拟某些内容,那么您可以
使用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()
关于python - 是否可以在 Django Behave 测试中进行模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38481881/