已解决 url 函数不等于 class 基于视图的 `as_view()` 方法?

Resolved url function not equal to class based view `as_view()` method?

我有以下测试:

def test_root_url_resolves_to_home_page_view(self):
    found = resolve('/')
    self.assertEqual(
        found.func,
        views.HomePageView.as_view()
    )

出现此错误:

AssertionError: <function HomePageView at 0x107d65620> != <function HomePageView at 0x107d97400>

根据 django 2 documentation on testing the response resolver

# class-based views need to be compared by name, as the functions
# generated by as_view() won't be equal
self.assertEqual(response.resolver_match.func.__name__, MyView.as_view().__name__)

你的情况:

self.assertEqual(
        found.func.__name__,
        views.HomePageView.as_view().__name__
    )

因为您使用的是基于 Class 的视图;你也可以这样做:

self.assertEqual(
    found.func.view_class,
    views.HomePageView
)