我对此感到困惑:我使用#Django 1.11.2。我在同一个测试类中有几个测试。它们(和实际代码)依赖于我使用迁移注入的数据。特别是,我创建了一些安全组。在./manage.py migrate
运行时,迁移工作完美。它们似乎也适用于课堂上的第一次测试。但是,当第二次测试运行setUp
时,它会抱怨该组不存在。这是我在测试类中的设置函数:
class MyDjangoTest(TestCase):
def setUp(self):
# Every test needs access to the request factory.
self.client = Client()
self.password = 'top_secret'
# ERROR: fails at this line in test_2 wit object not found exception, test_1 OK
group: Group = Group.objects.get_by_natural_key("SomeGroup")
self.user1: User = User.objects.create_user(
username='john', email='john@…', password=self.password)
self.user1.groups.add(group)
self.user2: User = User.objects.create_user(
username='jane', email='jane@…', password=self.password)
self.user2.groups.add(group)
def test_1(self):
# Executes just fine
doStuff()
def test_2(self):
# Throws an exception when fetching the group in setUp
doMoreStuff()