无法在DJANGO中完成基于Unittest类的视图

时间:2019-05-30 22:06:53

标签: python django python-3.x unit-testing python-unittest

如何使用django完成此视图单元测试? 我正在开始使用unittest,由于某种原因,我无法成功完成基于一流的视图测试。

models.py

class BookListView(ListView):
    model = Book
    context_object_name = 'books'
    template_name = 'snippets/list.html'

urls.py

from django.contrib import admin
from django.urls import path, include
from .views import (BookListView)
from . import views


app_name = 'snippets'
urlpatterns = [
    path('', views.index, name='book_list'),

views.py

from django.test import TestCase, Client
from django.urls import reverse
from snippets.models import Book
import json



class TestViews(TestCase):

    def setUp(self):
        self.client = Client()

    def test_book_list_GET(self):
        response = self.client.get(reverse('snippets:book_list'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'snippets/list.html')

以下是来自终端的反馈崩溃

self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200

----------------------------------------------------------------------
Ran 1 test in 0.061s

FAILED (failures=1)
Destroying test database for alias 'default'...

1 个答案:

答案 0 :(得分:0)

正如已经评论过的:

class TestViews(TestCase):

    def setUp(self):
        self.client = Client()

    def test_book_list_GET(self):
        response = self.client.get('snippets:book_list')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'snippets/list.html')

您需要在此处传递网址,并带有django.urls.utils.reverse,以便为您提供视图的相对网址