how to test a model that has a foreign key in django?
In your setupTestData method you have to create a User object, and pass it into the NewsLetter object create method.
@classmethod
def setUpTestData(cls):
#Set up non-modified objects used by all test methods
user = User.objects.create(<fill params here>)
NewsLetter.objects.create(NewsLetterID=1, Email='[email protected]', Connected=False,UserID=user)
For those who land here.
To write a test for a model that has a ForeignKey field, you need to create an instance of the model that the ForeignKey points to and then call save() on the ForeignKey instance, before applying it to the creation of your target model for the test.
eg. (simplified for brevity)
class BookTestCase(TestCase):
def test_fields_author_name(self):
author = Author(name="Mazuki Sekida")
author.save()
book = Book(name="Zen Training", author=author)
book.save()
# assertion example ...
record = Book.objects.get(id=1)
self.assertEqual(record.author.name, "Mazuki Sekida")
Very similar to what @Arpit Solanki answered, here's what I did:
from datetime import date
from django.test import TestCase
from ..models import Post, Author
class PostModelTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.author_ = 'Rambo'
cls.author = Author.objects.create(name=cls.author_)
cls.post = Post.objects.create(
title='A test', author=cls.author, content='This is a test.', date=date(2021, 6, 16))
def test_if_post_has_required_author(self):
self.assertEqual(self.post.author.name, self.author_)