Django 2.0 TestCase意外地为每个测试创建了Model对象

时间:2018-03-14 16:23:34

标签: django django-testing django-tests

我有一些测试,我需要一个使用Board.objects.create()创建的Board对象,以使一个Object具有主键1。但我已经想到,每个测试都有一个新对象,所以我在那里有例如'pk': 5。如果我添加更多测试,'pk': 5可能会出错,因为它会更改为'pk': 6。对于所有测试,如何仅使用'pk': 1创建一个Board对象?

我正在使用Django 2.0.3

from django.test import TestCase
from django.urls import reverse, resolve
from .views import home, board_topics, new_topic
from .models import Board

class BoardTopicsTests(TestCase):
    def setUp(self):
        Board.objects.create(name='Django', description='Django board.')

    def test_board_topics_view_success_status_code(self):
        url = reverse('boards:board_topics', kwargs={'pk': 5})
        response = self.client.get(url)
        self.assertEquals(response.status_code, 200)

    def test_board_topics_view_not_found_status_code(self):
        url = reverse('boards:board_topics', kwargs={'pk': 99})
        response = self.client.get(url)
        self.assertEquals(response.status_code, 404)

    def test_board_topics_url_resolves_board_topics_view(self):
        view = resolve('/boards/1/')
        self.assertEquals(view.func, board_topics)

    def test_board_topics_view_link_back_to_homepage(self):
        board_topics_url = reverse('boards:board_topics', kwargs={'pk': 3})
        response = self.client.get(board_topics_url)
        homepage_url = reverse('boards:home')
        self.assertContains(response, 'href="{0}"'.format(homepage_url))

    def test_board_topics_view_contains_navigation_links(self):
        board_topics_url = reverse('boards:board_topics', kwargs={'pk': 2})
        homepage_url = reverse('boards:home')
        new_topic_url = reverse('boards:new_topic', kwargs={'pk': 2})

        response = self.client.get(board_topics_url)

        self.assertContains(response, 'href="{0}"'.format(homepage_url))
        self.assertContains(response, 'href="{0}"'.format(new_topic_url))

1 个答案:

答案 0 :(得分:3)

您不应该依赖所创建对象的主键。在这种情况下,您可以将电路板存储为属性

def setUp(self):
    self.board = Board.objects.create(name='Django', description='Django board.')

然后在测试中使用它的pk。

def test_board_topics_view_success_status_code(self):
    url = reverse('boards:board_topics', kwargs={'pk': self.board.pk})

这将使您的测试套件更加强大。目前,如果运行测试的子集,或者以不同的顺序运行测试,则测试可能会失败。