Persist variable changes between tests in unittest?

后端 未结 4 1910
既然无缘
既然无缘 2020-12-08 13:22

How do I persist changes made within the same object inheriting from TestCase in unitttest?

from unittest import TestCase, main as unittest_main         


        
4条回答
  •  长情又很酷
    2020-12-08 14:13

    I like your own answer for the simplicity of it, but if you want to keep distinct unit tests:

    Apparently unittest runs separate tests with fresh instances of the TestCase. Well, just bind the objects to be persisted to something else but self. For example:

    from unittest import TestCase, main as unittest_main
    
    
    class TestSimpleFoo(TestCase):
    
        def setUp(self):
            pass
    
        def test_a(self):
            TestSimpleFoo.foo = 'can'
    
        def test_f(self):
            self.assertEqual(TestSimpleFoo.foo, 'can')
    
    
    if __name__ == '__main__':
        unittest_main()
    

    You might be interesed in setUpClass and tearDownClass too: https://docs.python.org/3/library/unittest.html#setupclass-and-teardownclass

    Also take care about the execution order of your unit tests: https://docs.python.org/2/library/unittest.html#unittest.TestLoader.sortTestMethodsUsing

提交回复
热议问题