Search code examples
djangounit-testingpython-unittest

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


Here is my code for unit test fruit view. But getting 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)

Solution

  • This method is part of django's TestCase class, so you need to use it instead:

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