Run setUp only once for a set of automated tests

前端 未结 8 1234
逝去的感伤
逝去的感伤 2020-12-13 05:15

My Python version is 2.6.

I would like to execute the test setUp method only once since I do things there which are needed for all tests.

My idea was to crea

相关标签:
8条回答
  • 2020-12-13 06:14

    If you ended up here because of need to load some data for testing... then as far as you are using Django 1.9+ please go for setUpTestData:

    class MyTests(TestCase):
    
        @classmethod
        def setUpTestData(cls):
            # Set up data for the whole TestCase
            cls.foo = Foo.objects.create(bar="Test")
    
        def test1(self):
            self.assertEqual(self.foo.bar, 'Test') 
    
    0 讨论(0)
  • 2020-12-13 06:16

    Daniel's answer is correct, but here is an example to avoid some common mistakes I found, such as not calling super() in setUpClass() when TestCase is a subclass of unittest.TestCase (like in django.test or falcon.testing).

    The documentation for setUpClass() doesn't mention that you need to call super() in such cases. You will get an error if you don't, as seen in this related question.

    class SomeTest(TestCase):
        def setUp(self):
            self.user1 = UserProfile.objects.create_user(resource=SomeTest.the_resource)
    
        @classmethod
        def setUpClass(cls):
            """ get_some_resource() is slow, to avoid calling it for each test use setUpClass()
                and store the result as class variable
            """
            super(SomeTest, cls).setUpClass()
            cls.the_resource = get_some_resource()
    
    0 讨论(0)
提交回复
热议问题