這是我的單元測驗水果視圖代碼。但是得到AttributeError
test_views.py
class TestViews(unittest.TestCase):
def test_fruit_GET(self):
client = Client()
response = client.get(reverse('products:fruit'))
self.assertEquals(response.status_code, 200)
self.assertTemplateUsed(response, 'products/fruit.html')
視圖.py
def fruit(request):
product = Product.objects.filter(category="Fruit")
n = Product.objects.filter(category="Fruit").count()
params = {'product': product, 'n': n}
return render(request, 'products/fruit.html', params)
uj5u.com熱心網友回復:
此方法是 django 的 TestCase 類的一部分,因此您需要改用它:
from django.test import TestCase
class TestViews(TestCase):
def test_fruit_GET(self):
client = Client()
response = client.get(reverse('products:fruit'))
self.assertEquals(response.status_code, 200)
self.assertTemplateUsed(response, 'products/fruit.html')
uj5u.com熱心網友回復:
這不適用于unittest.TestCase. 這是由 Django 的TestCase類 [Django-doc]提供的,所以:
from django.test import TestCase
class TestViews(TestCase):
def test_fruit_GET(self):
response = self.client.get(reverse('products:fruit'))
self.assertEquals(response.status_code, 200)
self.assertTemplateUsed(response, 'products/fruit.html')
你可以自己實作這個,但是很不方便:
def assertTemplateUsed(self, response, template_name):
self.assertIn(
template_name,
[t.name for t in response.templates if t.name is not None]
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/460510.html
