使用@classmethod在Django中创建对象以进行测试

2024-09-30 18:14:11 发布

您现在位置:Python中文网/ 问答频道 /正文

但是,哪种方法是创建测试对象的首选方法?为什么?你知道吗

说明:出于测试目的,即测试在test_models.py文件中创建的model

第一条路:

使用@classmethods

class AuthorModelTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        Author.objects.create(first_name="Big", last_name="Bob")

第二条路:

或者传递self而不是引用class

class AuthorModelTest(TestCase):
    def setUpTestData(self):
        Author.objects.create(first_name="Big", last_name="Bob")

Tags: 方法nameselfobjectsdefcreatetestcaseclass
1条回答
网友
1楼 · 发布于 2024-09-30 18:14:11

它在TestCase中被定义为classmethod,因此您应该在代码中执行同样的操作。也许这两个版本现在都可以工作,但是在Django的未来版本中,它会破坏您的代码与Django的兼容性。您可以检查documentation。你知道吗

classmethod TestCase.setUpTestData(): The class-level atomic block described above allows the creation of initial data at the class level, once for the whole TestCase.

只需遵循文档中的示例:

from django.test import TestCase

class MyTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        # Set up data for the whole TestCase
        cls.foo = Foo.objects.create(bar="Test")
        ...

相关问题 更多 >