【发布时间】:2015-10-24 21:07:38
【问题描述】:
这是我的代码:
我的导入链接在这里: https://github.com/django/django/blob/master/django/core/urlresolvers.py https://github.com/django/django/blob/master/django/contrib/auth/models.py https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/status.py https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/test.py
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APITestCase
class UserTests(APITestCase):
def test_create_user(self):
"""
Ensure we can create a new user object.
"""
url = reverse('user-list')
data = {'username': 'a', 'password': 'a', 'email': 'a@hotmail.com'}
# Post the data to the URL to create the object
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
# Check the database to see if the object is created.
# This check works.
self.assertEqual(User.objects.count(), 1)
def test_get_user(self):
"""
Ensure we can get a list of user objects.
"""
# This fails and returns an error
self.assertEqual(User.objects.count(), 1)
当我运行测试时,它会引发一个错误,提示 AssertionError: 0 != 1,因为在函数 test_get_user 中,在 test_create_user 中创建的用户不可见。有没有办法让一个类中的所有方法共享同一个数据库,这样如果我在test_create_user 中创建一个用户,我可以在它下面的方法中访问它?
编辑:我希望他们为所有方法共享同一个数据库的原因是因为我在 UserTests 类中的所有测试用例都需要创建一个用户,所以我不想重复相同的代码即使在 test_create_user 中进行测试,也始终如此。
我知道我可以使用def setUp(self),但我正在使用我的第一种方法进行“创建用户”测试,因此我希望能够测试我是否可以先创建它,然后再在def setUp(self) 中创建它。
【问题讨论】:
-
请添加
APITestCase和您的导入。 -
我认为为 unittest 用户创建一个单独的测试用例更容易。它基本上会测试用于创建用户的代码,这些代码可用于在其他测试用例中预填充数据库。
-
@SebastianWozny 我添加了 GitHub 源代码的链接(这是默认的 Django 和 DRF 源代码)。
-
@Ivan Hm,你到底是什么意思?你是说我创建自己的类来对
test_create_user进行单元测试,然后创建一个单独的类来对依赖于创建用户的其他所有内容进行单元测试(这样我就可以在def setUp(self)方法中创建用户?)。 -
没错,你不应该试图把所有东西都放在一个
TestCase中。
标签: python django unit-testing python-unittest django-unittest