简体   繁体   中英

Unit testing CRUD functions in Django

I am trying to create a basic unit test for my code. Here is what I'm running...

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')

The error I'm getting is "django.db.utils.IntegrityError: (1048, "Column 'author_id' cannot be null")" I believe the error is finding the user but when I run it in the shell it updates with no problems.

Django creates a separate database for tests which is initially empty. Thus, User.objects.first() returns None. You then pass None as author when you try to create a post.

You need to create a user here.

Alternatively, you can extend from SimpleTestCase rather than TestCase and use something like factory boy . It has a DjangoModelFactory class which you can use to create dummy Model objects which work just like the real instances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM