且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何测试Django CreateView?

更新时间:2023-12-04 09:08:10

您可以直接从数据库中获取它。

You can get it directly from the database.

请注意,您不应在测试中调用两个视图。每个测试应仅调用其实际测试的代码,因此这应该是两个单独的视图:一个调用创建视图并断言该条目位于数据库中,另一个视图直接创建一个条目然后将详细信息视图调用到检查它是否显示。因此:

Note, you shouldn't call two views in your test. Each test should only call the code it is actually testing, so this should be two separate views: one to call the create view and assert that the entry is in the db, and one that creates an entry directly and then calls the detail view to check that it displays. So:

def test_published_post(self):
    self.client.post('/post/compose/', {'author':"manualvarado22", 'title': "Super Important Test", 'content':"This is really important.", 'published_date':timezone.now()})
    self.assertEqual(Post.objects.last().title, "Super Important Test")

def test_display_post(self):
    post = Post.objects.create(...whatever...)
    response = self.client.get(reverse('blog:post_detail', pk=post.pk))
    self.assertContains(response, "really important")