多模型的Django测试用例编写
Django Test Case Writing for Multiple Models
最近几天我正在尝试编写 Django TestCase
,但我未能为多个模型编写测试用例
这是我的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)
我试过这样写 TestCase。
这是我的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))
谁能告诉我如何设计这个测试?非常感谢您的时间和关怀
author
是一个 ForeignKey
,因此您应该首先创建一个 Author
,然后传递对该 Author
对象的引用。 category
外键也一样:
class TestContactModel(TestCase):
def setUp(self):
self.author = <b>author</b> = Author.objects.create(name='Douglas Adams')
self.category = <b>category</b> = Category.objects.create(name='sci-fi')
self.article = Article.objects.create(
author=<b>author</b>,
title="The Hitchhiker's Guide to the Galaxy",
body='42',
category=<b>category</b>
)
最近几天我正在尝试编写 Django TestCase
,但我未能为多个模型编写测试用例
这是我的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)
我试过这样写 TestCase。
这是我的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))
谁能告诉我如何设计这个测试?非常感谢您的时间和关怀
author
是一个 ForeignKey
,因此您应该首先创建一个 Author
,然后传递对该 Author
对象的引用。 category
外键也一样:
class TestContactModel(TestCase):
def setUp(self):
self.author = <b>author</b> = Author.objects.create(name='Douglas Adams')
self.category = <b>category</b> = Category.objects.create(name='sci-fi')
self.article = Article.objects.create(
author=<b>author</b>,
title="The Hitchhiker's Guide to the Galaxy",
body='42',
category=<b>category</b>
)