<p>问题是您在类定义中创建用户。它在加载测试类时运行,在创建数据库之前。在</p>
<pre><code>class ExampleTest(LiveServerTestCase):
user = User.objects.create_superuser('Testuser','test@user.com','1234')
user.save() # This save isn't required it has been saved already
</code></pre>
<p>您可以通过将用户创建移动到单个测试中来解决该问题。然后,在创建数据库之后,当测试方法运行时,将创建用户。在</p>
^{pr2}$
<p>django1.8有一个<a href="https://docs.djangoproject.com/en/1.8/topics/testing/tools/#django.test.TestCase.setUpTestData" rel="nofollow">^{<cd1>}</a>方法,您可以在其中为整个测试用例设置一次初始数据。这样做更快,重复性更少。在</p>
<pre><code>class ExampleTest(LiveServerTestCase):
@classmethod
def setUpTestData(cls):
# Set up data for the whole TestCase
self.user = User.objects.create_superuser('Testuser','test@user.com','1234')
def test_user(self):
# access the user with self.user
...
</code></pre>
<p>在没有<code>setUpTestData</code>的Django的早期版本中,可以在<a href="https://docs.python.org/2/library/unittest.html#unittest.TestCase.setUp" rel="nofollow">^{<cd3>}</a>方法中创建用户。在</p>
<pre><code>class ExampleTest(LiveServerTestCase):
def setUp(self):
self.user = User.objects.create_superuser('Testuser','test@user.com','1234')
</code></pre>