1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
为了测试 `calculate_bmi` 函数,我们可以使用 `pytest` 框架,并结合 `pytest.mark.parametrize` 来实现参数化测试。以下是一个完整的测试用例,涵盖了正常情况和异常情况。
```python
import pytest
# 导入要测试的函数
from your_module import calculate_bmi
# 正常情况的测试用例
@pytest.mark.parametrize("weight, height, expected", [
(60, 1.75, "正常人"), # 正常BMI
(50, 1.75, "竹竿!"), # 低BMI
(80, 1.75, "壮士!"), # 高BMI
(100, 1.75, "肥宅!"), # 超高BMI
])
def test_calculate_bmi_normal(weight, height, expected):
assert calculate_bmi(weight, height) == expected
# 异常情况的测试用例
@pytest.mark.parametrize("weight, height, expected_exception", [
(0, 1.75, ValueError), # 体重为0
(60, 0, ValueError), # 身高为0
(-10, 1.75, ValueError), # 体重为负数
(60, -1.75, ValueError), # 身高为负数
])
def test_calculate_bmi_exceptions(weight, height, expected_exception):
with pytest.raises(expected_exception):
calculate_bmi(weight, height)
` ``
### 解释:
1. **正常情况测试**:
- 使用 `pytest.mark.parametrize` 来测试不同的体重和身高组合,验证函数返回的BMI分类是否正确。
- 测试用例包括正常BMI、低BMI、高BMI和超高BMI的情况。
2. **异常情况测试**:
- 测试函数在输入无效值(如体重或身高为0或负数)时是否抛出 `ValueError` 异常。
- 使用 `pytest.raises` 来捕获预期的异常。
### 运行测试:
确保你已经安装了 `pytest`,然后在终端中运行以下命令来执行测试:
```bash
pytest test_bmi.py
` ``
### 注意:
- `your_module` 是包含 `calculate_bmi` 函数的模块名,请根据实际情况替换。
- 测试文件通常命名为 `test_*.py` 或 `*_test.py`,以便 `pytest` 自动识别并运行测试。
|