[Django]-Django Testing: URL mapping to the Class Based View

5πŸ‘

I was stung by this issue just now, ended up finding the solution in the documentation

class-based views need to be compared by name, as the functions generated by as_view() won’t be equal due to different object ids, so the assertion should look like the below:

from django.test import TestCase
from django.urls import resolve
from .views import HomePageView

class HomePageViewViewTest(TestCase):
    def test_resolve_to_home_page_view(self):
        resolver = resolve('/')
        self.assertEqual(resolver.func.__name__, HomePageView.as_view().__name__)

3πŸ‘

from django.urls import resolve, reverse
class HomePageViewViewTest(TestCase):
def test_resolve_to_home_page_view(self):
    resolver = resolve('/')
    self.assertEqual(resolver.func.view_class, HomePageView)

You can try this, it worked for me!

0πŸ‘

Since you are testing a Class based View, from the Traceback it can be seen that it’s missing the request object. You can use the RequestFactory provided by the django.test package. Better read the following RequestFactory Documentation to get a good view of it. It will solve your problem.

πŸ‘€AR7

-1πŸ‘

from django.urls import resolve, reverse


class HomePageTest(TestCase):
    def test_root_url_resolves_to_home_page_view(self):
        response = self.client.get(resolve('/'))
        response = self.client.get(reverse('your_app_name:list'))
        self.assertEqual(response.status_code, 200)
πŸ‘€user13964893

Leave a comment