Search code examples
djangodjango-testingdjango-tests

Django Test Case Writing for Multiple Models


I am trying to write Django TestCase for last few days but i failed to write testcase for multiple models

this is my models.py

from django.db import models
from django.contrib.auth.models import User

class Author(models.Model):
    name = models.TextField(max_length=50)

class Category(models.Model):
    name = models.CharField(max_length=100)

class Article(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    body = models.TextField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

And i tried to write TestCase like this.

this is my tests.py

from django.test import TestCase
from blog.models import Article, Author, Category


class TestContactModel(TestCase):
    def setUp(self):
        self.article = Article(author='jhon', title='how to test', body='this is body', category='djangooo')
        self.article.save()

    def test_contact_creation(self):
        self.assertEqual(article.objects.count(), 1)

    def test_contact_representation(self):
        self.assertEqual(self.article.title, str(self.article))

Can anyone tell me how can i craft this test? Your time and caring is much appreciated


Solution

  • The author is a ForeignKey, so you should first create an Author, and then pass a reference to that Author object. The same for the category foreign key:

    class TestContactModel(TestCase):
    
        def setUp(self):
            self.author = author = Author.objects.create(name='Douglas Adams')
            self.category = category = Category.objects.create(name='sci-fi')
            self.article = Article.objects.create(
                author=author,
                title="The Hitchhiker's Guide to the Galaxy",
                body='42',
                category=category
            )