LoginSignup
7
8

More than 5 years have passed since last update.

Djangoでテストデータを作成するときはsetUpTestDataを使う

Posted at

setUpでテストデータを作成すると

test_data.py
from test.common_data import UserFactory


class Test(TestCase):

    def setUp(self):
        self.user = UserFactory.create()

    def test_1(self):
        print(self.user.pk) # 1

    def test_2(self):
        print(self.user.pk) # 2

クラス内のメソッドの数だけデータを作成してしまう。

setUpTestDataを使う

test_data.py
from test.common_data import UserFactory


class Test(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.user = UserFactory.create()

    def test_1(self):
        print(self.user.pk) # 1

    def test_2(self):
        print(self.user.pk) # 1

うれしい!!!

参考

How to optimize Django unit tests with setUpTestData
http://makina-corpus.com/blog/metier/2015/how-to-optimize-django-unit-tests-with-setuptestdata

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8