在模型中为 __str__ 编写 Django 测试

writing djnago test for __str__ in a model

我想测试我的博客应用程序。在 运行 覆盖后,我有大约 91%,但有 4 个缺失。报道指出下面的代码行丢失了。

def publish(self):
        self.published_date=timezone.now()
        self.save()

    def __str__(self):
        return self.title

因此,我决定为 str(self) 编写一个测试。

这是测试的样子

class PostTest(TestCase):

    def create_post(self, title="only a test", text="Testing if the created title matches the expected title"):
        return Post.objects.create(title=title, text=text, created_date=timezone.now())

    def test_post_creation(self):
        w = self.create_post()
        self.assertTrue(isinstance(w, Post))
        self.assertEqual(str(w), w.title)

测试失败并出现以下错误。

django.db.utils.IntegrityError: null value in column "author_id" violates not-null constraint
DETAIL:  Failing row contains (1, only a test, Testing if the created title matches the expected title, 2020-05-31 05:31:21.106429+00, null, null, 0, null, 2020-05-31 05:31:21.108428+00, ).

这是模型的样子:

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True, blank= True, null=True)
    updated_on = models.DateTimeField(auto_now= True)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)
    status = models.IntegerField(choices=STATUS, default=0)
    photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)

    class Meta:
        ordering = ['-published_date']

    def publish(self):
        self.published_date=timezone.now()
        self.save()

    def __str__(self):
        return self.title

你建议我如何编写测试来修复此错误并提高覆盖率?

问题是你需要通过一个作者来创建一个post:

class PostTest(TestCase):
    def create_post(self, title="only a test", text="Testing if the created title matches the expected title"):
        # The arguments passed to initialize the user depend on your User model
        author = User.objects.create(username='username', first_name='first_name', last_name='last_name', email='email@gmail.com' password='Password0')
        return Post.objects.create(title=title, text=text, created_date=timezone.now())

    def test_post_creation(self):
        w = self.create_post()
        self.assertTrue(isinstance(w, Post))
        self.assertEqual(str(w), w.title)