Skip to main content
 首页 » 编程设计

python之Django 单元测试之创建对象的 ID

2024年09月03日41dyllove98

示例模型.py

模型.py

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

假设我已经编写了单元测试:

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 开始,依此类推?如果不是,是否有特定原因导致测试数据库在运行所有测试后总是被破坏?

请您参考如下方法:

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

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

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