0Pricing
Django Academy · 课时

编写 TestCase 与断言

自动测试模型和视图

编写 TestCase 与断言 是 CoddyKit 上的免费 Django Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Django Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Django Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Write Tests?

Tests catch bugs before your users do. They let you change code with confidence, knowing a green run means nothing broke. ✅

Meet TestCase

Django gives you a TestCase base class. Subclass it and each method that starts with test_ becomes an automatic check.

from django.test import TestCase

Your First Test Class

Group related checks in one class. Here a TestCase subclass will hold all the tests for the Article model.

class ArticleTests(TestCase):
    pass

A Fresh Database

TestCase runs each test in its own transaction and rolls it back afterward. Tests never pollute your real data or each other.

Writing a Test Method

Name every test method with a test_ prefix so Django's runner discovers and executes it for you.

def test_title_is_saved(self):
    ...

Assert Equality

The classic check is assertEqual. It passes when two values match and fails loudly when they differ.

self.assertEqual(article.title, 'Hello')

Assert True or False

For boolean conditions use assertTrue and assertFalse. They make intent crystal clear in your test.

self.assertTrue(article.is_published)

Setting Up Shared Data

Need the same object in many tests? Build it once in setUp, which Django runs before every test method.

def setUp(self):
    self.a = Article.objects.create(title='Hi')

Testing a Model Method

Verify your model behaves as designed. Create an object, call its method, then assert the result is what you expect.

self.assertEqual(str(self.a), 'Hi')

Run the Tests

Kick everything off with the test command. Django finds your test files, runs them, and reports passes and failures.

python manage.py test

Reading the Output

A dot means a pass, an F means a failure, and E means an error. The summary shows exactly which test broke and why.

Quick Check

Django needs to know which methods are tests.

Recap

You wrote a TestCase, used setUp for shared data, checked results with assertEqual and assertTrue, and ran it all with manage.py test. 🎉

常见问题解答

「编写 TestCase 与断言」课时是免费的吗?

是的 — 「编写 TestCase 与断言」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Django Academy 课程的其余内容,请升级到 CoddyKit PRO。 Django Academy 课程共包含 4 节课。

「编写 TestCase 与断言」这节课中我会学到什么?

自动测试模型和视图 你通过在浏览器中直接运行的动手代码来练习 Django Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Django Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Django Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「编写 TestCase 与断言」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Django Academy 课中编写并运行代码吗?

能。每节 Django Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Paginator 类
  2. ListView 中的分页控件
  3. 编写 TestCase 与断言
  4. 测试客户端与装置
← 返回 Django Academy