如何在pytestbdd里面去写测试用例
时间: 2023-08-06 12:07:14 浏览: 46
在 pytest-bdd 中编写测试用例可以按照以下步骤进行:
1. 安装 pytest-bdd:
```
pip install pytest-bdd
```
2. 创建一个测试目录,并在该目录下创建一个 `features` 文件夹用于存放特性文件和一个 `steps` 文件夹用于存放步骤定义文件。
3. 在 `features` 文件夹中创建一个特性文件,例如 `my_feature.feature`,并在其中定义你的测试场景和步骤。
例如:
```gherkin
Feature: My Feature
Scenario: My Scenario
Given I have a calculator
When I add 2 and 3
Then the result should be 5
```
4. 在 `steps` 文件夹中创建一个步骤定义文件,例如 `test_my_feature.py`,并在其中编写测试步骤的实现。
例如:
```python
from pytest_bdd import given, when, then
@given("I have a calculator")
def i_have_a_calculator():
# 实现步骤逻辑
pass
@when("I add <num1> and <num2>")
def i_add_num1_and_num2(num1, num2):
# 实现步骤逻辑
pass
@then("the result should be <result>")
def the_result_should_be_result(result):
# 实现步骤逻辑
pass
```
5. 在测试目录下创建一个 `conftest.py` 文件,用于配置 pytest-bdd。
例如:
```python
from pytest_bdd import scenarios
scenarios("features")
```
6. 运行测试用例:
```
pytest
```
这样,你就可以使用 pytest-bdd 编写和运行测试用例了。记得根据你的需要适当修改特性文件和步骤定义文件中的内容。希望对你有所帮助!