You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pytest正确测试Django模型的age属性并实现全覆盖率

解决方案:用@pytest.mark.parametrize覆盖分支逻辑

直接使用@pytest.mark.parametrize定义多组测试用例,分别覆盖年龄<18和年龄≥18的分支,无需在测试中加条件判断,每个用例独立验证,自然覆盖所有逻辑,且不用新增测试文件。

测试代码示例

假设你的测试文件是tests/test_models.py,在其中添加或修改测试函数即可:

import pytest
from datetime import date
from yourapp.models import TravelFriend

@pytest.mark.django_db
@pytest.mark.parametrize(
    "birth_date, expected_age",
    [
        # 案例1:年龄小于18,返回数值(生日已过)
        (date(date.today().year - 17, date.today().month, date.today().day), 17),
        # 案例2:年龄小于18,返回数值(生日未过)
        (date(date.today().year - 17, date.today().month, date.today().day + 1), 16),
        # 案例3:年龄等于18,返回'18+'(生日已过)
        (date(date.today().year - 18, date.today().month, date.today().day), '18+'),
        # 案例4:年龄大于18,返回'18+'
        (date(date.today().year - 25, date.today().month, date.today().day), '18+'),
    ]
)
def test_travel_friend_age(birth_date, expected_age):
    travel_friend = TravelFriend.objects.create(birth_date=birth_date)
    assert travel_friend.age == expected_age

关键说明

  • @pytest.mark.parametrize会自动为每组(birth_date, expected_age)生成独立测试用例,分别验证不同分支场景。
  • 加入「生日未过」的案例,能确保年龄计算逻辑的准确性,避免因生日日期导致的判断错误。
  • 运行测试后,用pytest --cov=yourapp查看覆盖率报告,即可确认age属性的所有分支已被完全覆盖。

内容的提问来源于stack exchange,提问作者WEBBOgrafico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 22:24:54