一种方法是reverse
URL 名称并验证
例子
urlpatterns = [
url(r'^archive/(\d{4})/$', archive, name="archive"),
url(r'^archive-summary/(\d{4})/$', archive, name="archive-summary"),
]
现在,在测试中
from django.urls import reverse
url = reverse('archive', args=[1988])
assertEqual(url, '/archive/1988/')
url = reverse('archive-summary', args=[1988])
assertEqual(url, '/archive-summary/1988/')
无论如何,您可能正在测试视图。
现在,要测试 URL 是否连接到正确的视图,您可以使用resolve
from django.urls import resolve
resolver = resolve('/summary/')
assertEqual(resolver.view_name, 'summary')
现在在变量resolver
(ResolverMatch
类实例)中,您有以下选项
'app_name',
'app_names',
'args',
'func',
'kwargs',
'namespace',
'namespaces',
'url_name',
'view_name'