python - 是否可以在 Django Behave 测试中进行模拟?

标签 python django mocking python-mock python-behave

我看过很多关于使用模拟进行单元测试的文章。

我有一个简单的结帐表单,可将​​卡详细信息提交到支付网关。是否可以模拟 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/

相关文章:

python - 窗口颜色/在 pygame 中添加一艘船

python - Django OneToOneField,ManyToManyField,外键

java - Stubbing 一个带有副作用的 void 方法

java - 使用 Mockito 捕获两个参数

python - 从(或接近)具有相同名称的脚本导入库会引发 "AttributeError: module has no attribute"或 ImportError 或 NameError

python - BeautifulSoup - 属性错误: 'NavigableString' object has no attribute 'find_all'

java - Cython/Jython 是一种独立的语言吗?

Javascript 和 Django 'static' 模板标签

python - 不能 "activate"virtualenv

mocking - 任何关于 FakeItEasy 的好教程