Django 单元测试 - 创建对象的 ID

Django Unit Test - IDs of created objects

样本models.py

models.py

class Food(models.Model):
    name = models.CharField(max_length=50, verbose_name='Food')

    def __str__(self):
        return self.name

假设我写了单元test/s:

from django.test import TestCase
from myapp.models import Food

class TestWhateverFunctions(TestCase):
    """
    This class contains tests for whatever functions.
    """

    def setUp(self):
        """
        This method runs before the execution of each test case.
        """
        Food.objects.create(name='Pizza') # Will the created object have id of 1?
        Food.objects.create(name='Pasta') # Will the created object have id of 2?

    def test_if_food_is_pizza(self):
        """
        Test if the given food is pizza.
        """
        food = Food.objects.get(id=1)

        self.assertEqual(food.name, 'Pizza')

    def test_if_food_is_pasta(self):
        """
        Test if the given food is pasta.
        """
        food = Food.objects.get(id=2)

        self.assertEqual(food.name, 'Pasta')

我想知道是否可以安全地假设 setUp() 方法 中创建的对象的 ID 总是从 id 1 开始,依此类推?如果不是,是否有特定原因为什么在 运行 所有测试之后测试数据库总是 destroyed

假设 ID 总是从 1 开始并递增是安全的。如果其他测试事先有 运行 并创建了 Food 行,并且单元测试未按任何保证顺序执行,则它们可能具有更高的 ID。

在您的测试设置中保存对模型实例的引用:

class TestWhateverFunctions(TestCase):

    def setUp(self):
        self.food1 = Food.objects.create(name='Pizza')
        self.food2 = Food.objects.create(name='Pasta')

感谢您提供了很好的示例。对于像我这样的新手,我使用了:

self.food1.id

作为测试URL的请求和响应的主键。