我正在改编官方 Django 1.5 教程中的单元测试。我正在尝试测试 ListView 上的空上下文。我收到以下错误:
AssertionError: Couldn't find 'No persons are available' in response.
这是我的 ListView 代码:
class RsvpListView(generic.ListView):
template_name = 'rsvp_list.html'
context_object_name = 'rsvplist'
def get_queryset(self):
return Person.objects.all()
这是我的测试用例方法:
def test_rvsp_list_view_with_no_persons(self):
response = self.client.get(reverse('myapp:rsvp_view'))
self.assertEqual(response.status_code,200)
self.assertContains(response,"No persons are available.")
self.assertQuerysetEqual(response.context['rsvplist'],[])
但在官方教程中,Polls 有等效的行(https://docs.djangoproject.com/en/dev/intro/tutorial05/#testing-our-new-view):
self.assertContains(response,"No polls are available.")
我不知道教程提供的 View 方法的响应中“没有可用的民意调查”存储在哪里,但由于某种原因它通过了——虽然我的没有通过。
我的测试方法中缺少什么所以它也通过了?
最佳答案
“没有可用的投票”消息来自模板。来自 part 3 of the tutorial :
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
您需要更新您的模板 rsvp_list.html 以包含“No persons are available”。以类似的方式。
关于Django:单元测试 ListView 和 assertContains 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18070226/