HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

01-模型层(models)

第 37 / 42 段:测试

Django 风格指南 (HackSoft) · 发布 2026-02-05 · 更新 2026-11-11 · 标签:Django、Models、数据库设计

测试(续)

💡 小贴士:关于测试框架的选择

这里的示例为了保持全栈框架的零依赖通用性,使用了 Django 内置的 TestCase。但在实际的工程项目中,我们强烈建议你使用 pytest 及其插件 pytest-django 来编写测试。内置的 unittest 风格往往需要继承繁琐的大类,且断言语法较为陈旧;而 pytest 能让你的测试代码更简洁、更具可读性。详见 06_测试和 Celery 章节。

这里要注意几件事:

  1. 我们断言如果调用 full_clean,将会抛出验证错误。
  2. 我们根本没有访问数据库,因为没有必要。这可以加速某些测试。

💡 不访问数据库的好处

# ✅ 快速测试:不访问数据库
def test_property_calculation(self):
    order = Order(subtotal=100, tax_rate=0.1)
    self.assertEqual(order.tax_amount, Decimal('10'))
    # 没有 .save(),测试更快

# ⚠️ 慢速测试:访问数据库
def test_with_database(self):
    order = Order.objects.create(subtotal=100, tax_rate=0.1)
    self.assertEqual(order.tax_amount, Decimal('10'))
    # 涉及数据库操作,较慢