当我根据教程'AssertionError:404!= 200'测试简单的应用程序时。任何人都可以解决这个问题吗? (项目名称: simple_project ,项目内的应用名称:页面)
我的应用级别urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('about/', views.AboutPageView.as_view(), name='about'),
]
我的应用级别views.py:
from django.views.generic import TemplateView
class HomePageView(TemplateView):
template_name = 'home.html'
class AboutPageView(TemplateView):
template_name = 'about.html'
我的项目级别urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('pages.urls')),
]
我的tests.py:
from django.test import SimpleTestCase
class SimpleTests(SimpleTestCase):
def test_home_page_status_code(self):
response = self.client.get('/')
self.assertEquals(response.status_code, 200)
def test_abaout_page_status_code(self):
response = self.client.get('about')
self.assertEquals(response.status_code, 200)
当我测试时,会发生此错误:
FAIL: test_abaout_page_status_code (pages.tests.SimpleTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\User\Dj\simple\pages\tests.py", line 10, in test_abaout_page_status_code
self.assertEquals(response.status_code, 200)
AssertionError: 404 != 200
答案 0 :(得分:0)
def test_abaout_page_status_code(self):
response = self.client.get('/about/')
self.assertEquals(response.status_code, 200)
试试这个
答案 1 :(得分:0)
我遇到了这样的问题,请使用:
from django.test import TestCase
from django.urls import reverse
def test_abaout_page_status_code(self):
response = self.client.get(reverse("about"))
self.assertEqual(response.status_code, 200)
答案 2 :(得分:0)
好吧,尝试一下:
from django.urls import reverse, resolve
from django.test import SimpleTestCase
from .views import HomePageView,AboutPageView
class SimpleTests(SimpleTestCase):
def test_home_page_status_code(self):
path = reverse("home")
self.assertEquals(resolve(path).func.view_class, HomePageView)
response = self.client.get(path)
self.assertEquals(response.status_code, 200)
def test_abaout_page_status_code(self):
path = reverse("about")
self.assertEquals(resolve(path).func.view_class, AboutPageView)
response = self.client.get(path)
self.assertEquals(response.status_code, 200)
答案 3 :(得分:-1)
使用我的代码,这肯定可以!!
from django.test import TestCase
def test_home_page_status_code(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_about_page_status_code(self):
response = self.client.get('/about/')
self.assertEqual(response.status_code, 200)