Behave 简明教程

Behave - Background

Background 用于为一群步骤添加组。它接近一个场景。我们可以使用 Background 向多个场景添加一个上下文。它在每个特征的场景之前运行,但在执行之前的钩子之后运行。

Background 通常用于执行前提条件,例如登录场景或数据库连接等。

可以添加 Background 描述,以便人类更好理解。它在特征文件中的只出现一次,并且必须在场景或场景大纲之前声明。

不应该使用 Background 来创建复杂的状态(只有在无法避免的情况下才使用)。该段落应该简洁且真实。另外,我们应该避免在一个特征文件中包含大量场景。

Feature File with Background

以下是标题为“payment process”的特征的包含 background 的特征文件−

Feature − Payment Process
   Background:
      Given launch application
      Then Input credentials
   Scenario − Credit card transaction
      Given user is on credit card payment screen
      Then user should be able to complete credit card payment
   Scenario − Debit card transaction
      Given user is on debit card payment screen
      Then user should be able to complete debit card payment

Corresponding Step Implementation File

该文件如下所示−

from behave import *
@given('launch application')
def launch_application(context):
   print('launch application')
@then('Input credentials')
def input_credentials(context):
   print('Input credentials')
@given('user is on credit card payment screen')
def credit_card_pay(context):
   print('User is on credit card payment screen')
@then('user should be able to complete credit card payment')
def credit_card_pay_comp(context):
   print('user should be able to complete credit card pay')
@given('user is on debit card payment screen')
def debit_card_pay(context):
   print('User is on debit card payment screen')
@then('user should be able to complete debit card payment')
def debit_card_pay_comp(context):
   print('user should be able to complete debit card payment')

Output

以下是运行特征文件后获得的输出,这里使用的命令为 behave --no-capture -f plain

feature file with background

后续输出如下所示 −

background

输出显示 Background 步骤(Given 启动应用程序和 Then 输入凭据)在每个场景之前运行了两次。