behave的基本用法

behave的基本用法

Behave 基本用法指南

Behave 是一个基于 Python 的行为驱动开发(BDD)框架,它使用自然语言风格的测试用例来描述系统的行为。通过结合 Gherkin 语法编写的特性文件(feature files),开发者可以轻松地编写、组织和执行测试。以下是如何开始使用 Behave 的一些基本步骤和示例。

安装 Behave

首先,你需要确保你的系统上安装了 Python 和 pip。然后,你可以通过 pip 来安装 behave:

pip install behave

创建项目结构

一个典型的 Behave 项目结构可能如下所示:

my_behave_project/ │ ├── features/ │ ├── steps/ │ │ └── my_steps.py │ └── example.feature │ └── requirements.txt
  • features/ 目录包含所有的特性文件(.feature)。
  • steps/ 目录包含实现这些特性的步骤定义文件(.py)。

编写特性文件

在 features/ 目录下创建一个名为 example.feature 的文件,并添加以下内容:

Feature: Addition of two numbers In order to avoid manual calculation As a user I want to add two numbers using a calculator Scenario: Add positive numbers Given I have entered 5 into the calculator And I have also entered 7 into the calculator When I press add Then the result should be 12 on the screen

这个特性文件描述了一个简单的加法功能。

实现步骤定义

接下来,在 features/steps/ 目录下创建一个名为 my_steps.py 的文件,并添加以下代码来实现上述特性文件中的步骤:

from behave import * @given('I have entered {num1} into the calculator') def step_enter_number_into_calculator(context, num1): context.numbers = [] context.numbers.append(int(num1)) @given('I have also entered {num2} into the calculator') def step_enter_second_number_into_calculator(context, num2): context.numbers.append(int(num2)) @when('I press add') def step_press_add(context): context.result = sum(context.numbers) @then('the result should be {expected} on the screen') def step_verify_result(context, expected): assert context.result == int(expected), f"Failed, got {context.result}"

每个装饰器(如 @given, @when, @then)都对应一个特定的步骤类型,并且会匹配特性文件中相应的步骤文本。

运行测试

在项目根目录(即包含 features/ 目录的目录)下运行以下命令来执行测试:

behave

你应该会看到类似以下的输出,表明测试是否成功:

Feature: Addition of two numbers # features/example.feature:1 In order to avoid manual calculation As a user I want to add two numbers using a calculator Scenario: Add positive numbers # features/example.feature:6 Given I have entered 5 into the calculator # features/steps/my_steps.py:4 0.000s And I have also entered 7 into the calculator # features/steps/my_steps.py:9 0.000s When I press add # features/steps/my_steps.py:13 0.000s Then the result should be 12 on the screen # features/steps/my_steps.py:18 0.000s 1 feature passed, 0 failed, 0 skipped 1 scenario passed, 0 failed, 0 skipped 4 steps passed, 0 failed, 0 skipped, 0 undefined Took 0m0.001s

结论

通过以上步骤,你已经成功地设置了一个基本的 Behave 测试项目,编写了特性文件和对应的步骤定义,并运行了测试。随着你对 Behave 的熟悉程度加深,你可以探索更多高级功能,如背景(Background)、参数化场景等,以更好地满足你的测试需求。