【发布时间】:2019-11-05 09:02:07
【问题描述】:
尝试使用assertQuerysetEqual在 Django TestCase 中测试响应上下文,但它失败了。
我尝试打印 Country.objects.all().count() 和 response.context['countries'].count() 的计数。当我在测试开始时创建一条记录时,两者都返回 1。
还在断言方法上尝试了ordered=True,但没有运气仍然未能通过测试。我错过了什么或需要以其他方式做吗?
返回响应的视图
class CountriesListView(generic.ListView):
model = Country
template_name = 'management/countries/countries.html'
context_object_name = 'countries'
使用测试
class CountryTest(TestCase):
def setUp(self):
self.countries_list_url = '/countries'
def test_response_returns_countries_context(self):
Country.objects.create(
name='India',
iso_3166_1='IN'
)
response = self.client.get(self.countries_list_url)
self.assertQuerysetEqual(Country.objects.all(), response.context['countries'])
我遇到的错误
AssertionError: Lists differ: ['<Country: Country object (1)>'] != [<Country: Country object (1)>]
First differing element 0:
'<Country: Country object (1)>'
<Country: Country object (1)>
- ['<Country: Country object (1)>']
? - -
+ [<Country: Country object (1)>]
遇到同样的错误
self.assertQuerysetEqual(Country.objects.all(), Country.objects.all())
【问题讨论】:
-
到目前为止在断言错误中注意到字符串语法
标签: django django-testing