简体   繁体   中英

Django's TestCase.setUp not working as anticipated

class Dummy(TestCase):
    def setUp(self):
        thing = Thing.objects.create(name="Thing")

    def test_a(self):
       self.assertTrue(Thing.objects.get(pk=1))

    def test_b(self):
       self.assertTrue(Thing.objects.get(pk=1))

In this example I expect for setUp to be run prior to every test case, but it is only run prior to the first and then the changes are rolled back. This causes test_a to pass, but the equivalent test_b to fail. Is this the expected behavior? What do I need to do to make sure that the database is in the same state prior to every test case?

Figured it out. setUp is being run each time, it's just that it's incrementing the private key in the database. Therefore the Thing with pk=1 no longer exists. This works just fine:

class Dummy_YepThatsMe(TestCase):
    def setUp(self):
        thing = Thing.objects.create(name="Thing")

    def test_a(self):
       self.assertTrue(Thing.objects.get(name="Thing"))

    def test_b(self):
       self.assertTrue(Thing.objects.get(name="Thing"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM