我正在尝试为我的代码创建一个基本的单元测试。这是我正在运行的...
from django.test import TestCase
from django.contrib.auth.models import User
from feed.models import Post
class PostTests(TestCase):
def setUp(self):
user = User.objects.first()
Post.objects.create(title='test', content='more testing', author=user)
def test_content(self):
post = Post.objects.get(id=1)
expected_object_name = f'{post.content}'
self.assertEquals(expected_object_name, 'more testing')
我得到的错误是“django.db.utils.IntegrityError: (1048, “Column 'author_id' cannot be null”)”我相信错误是在寻找用户但是当我在 shell 中运行它时更新没有问题。
最佳答案
Django 为测试创建了一个单独的数据库,该数据库最初是空的。因此,User.objects.first()
返回 None。然后,当您尝试创建帖子时,将 None
作为 author
传递。
您需要在这里创建一个用户。
或者,您可以从 SimpleTestCase
而不是 TestCase
进行扩展,并使用类似 factory boy 的东西.它有一个 DjangoModelFactory
类,您可以使用它来创建像真实实例一样工作的虚拟 Model
对象。
关于django - Django 中的单元测试 CRUD 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53839058/