Getting AttributeError: 'TestCase' object has no attribute 'assertTemplateUsed' when trying to unit test views.py using unittest framework

Getting AttributeError: 'TestCase' object has no attribute 'assertTemplateUsed' when trying to unit test views.py using unittest framework

这是我的单元测试水果视图代码。但是得到 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')

views.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)

这个方法是django的TestCase的一部分class,所以你需要改用它:

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')

这不适用于 unittest.TestCase。这是Django的TestCase class [Django-doc]提供的,所以:

from django.test import <strong>TestCase</strong>

class TestViews(<strong>TestCase</strong>):

    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]
    )