解析的url函数不等于基于类的视图`as_view()`方法?

时间:2017-12-25 12:17:32

标签: django django-testing

我有以下测试:

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>

2 个答案:

答案 0 :(得分:0)

根据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__
    )

答案 1 :(得分:0)

由于您正在使用基于类的视图;您也可以这样做:

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