2

我看过很多关于带有模拟的单元测试的文章。

我有一个简单的结帐表格,可以将卡详细信息提交到支付网关。是否可以在行为测试中模拟支付网关响应?

@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"

我想知道,是否可以在行为测试中进行模拟?

4

2 回答 2

3

确实是!

如果您只需要在步骤期间模拟某些内容,那么您可以使用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()
于 2018-10-08T22:00:25.613 回答
0

你可以试试:

@then(u'I submitted checkout form')
def submit_checkout_form(context):
    with mock.patch('path.module', mock.Mock(return_value=None)):
        **type here**
于 2017-06-08T23:11:58.830 回答