如何用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
相关产品推荐
相关产品推荐

