我正在尝试运行以下测试,但我不确定为什么它不工作,因为在运行测试时,创建了一个测试数据库,这意味着新创建的项的id为1,但我仍然收到一个错误,即没有对象与查询匹配
模型
from django.db import models
# Create your models here.
class Post(models.Model):
text = models.TextField()
def __str__(self):
return self.text[:50]
测验
from django.test import TestCase
from .models import Post
# Create your tests here.
class PostModelTest(TestCase):
def setup(self):
post = Post.objects.create(text="just a test")
def test_text_content(self):
post = Post.objects.get(id=1)
expected_obect_name = f'{post.text}'
self.assertEqual(expected_obect_name, 'just a test')
首先,您应该将方法命名为^{} 而不是
setup
。这是很敏感的。但这可能无法解决您的问题,因为django不会为每个TestCase
类重置自动id。因此,如果您有另一个具有相同代码的测试用例,那么错误将再次发生。要解决此问题,您需要将post id保存为,例如self.post_id
,并在测试方法中使用它,而不是1
:相关问题 更多 >
编程相关推荐