diff options
| author | Tim Schilling <schillingt@better-simple.com> | 2026-05-29 14:37:29 -0500 |
|---|---|---|
| committer | Jacob Walls <jacobtylerwalls@gmail.com> | 2026-06-15 15:30:40 -0400 |
| commit | d80ef32eb9e669986ed7838296f6373af56c68f0 (patch) | |
| tree | 7632257e53d0f9d9d783900f45bcf83bcd8d7757 | |
| parent | f1440a752ec034277ccdad914995c3f164308e41 (diff) | |
Fixed #37128 -- Doc'd setUpTestData as test speed up.
Revises the AnimalTestCase to better show test data isolation
and avoid the opportunity to use setUpTestData.
| -rw-r--r-- | docs/topics/testing/overview.txt | 16 |
1 files changed, 13 insertions, 3 deletions
diff --git a/docs/topics/testing/overview.txt b/docs/topics/testing/overview.txt index 8ec1652ba3..39a6843c02 100644 --- a/docs/topics/testing/overview.txt +++ b/docs/topics/testing/overview.txt @@ -30,16 +30,17 @@ transaction to provide isolation:: class AnimalTestCase(TestCase): def setUp(self): - Animal.objects.create(name="lion", sound="roar") Animal.objects.create(name="cat", sound="meow") def test_animals_can_speak(self): """Animals that can speak are correctly identified""" - lion = Animal.objects.get(name="lion") cat = Animal.objects.get(name="cat") - self.assertEqual(lion.speak(), 'The lion says "roar"') self.assertEqual(cat.speak(), 'The cat says "meow"') + cat.sound = "hiss" + cat.save(update_fields=["sound"]) + self.assertEqual(cat.speak(), 'The cat says "hiss"') + When you :ref:`run your tests <running-tests>`, the default behavior of the test utility is to find all the test case classes (that is, subclasses of :class:`unittest.TestCase`) in any file whose name begins with ``test``, @@ -386,3 +387,12 @@ Avoiding disk access for media files The :class:`~django.core.files.storage.InMemoryStorage` is a convenient way to prevent disk access for media files. All data is kept in memory, then it gets discarded after tests run. + +Using ``setUpTestData`` to create test data +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Moving common test data to :meth:`TestCase.setUpTestData` will reduce the +number of times your tests need to create the data. Using +:meth:`TestCase.setUpTestData` to will create test data +once per class. While :meth:`TestCase.setUp() <unittest.TestCase.setUp>` will +create the test data once per test. |
