how to specify test specific setup and teardown in python unittest

后端 未结 1 601
旧时难觅i
旧时难觅i 2021-01-29 11:05

I want to create unittest test with two different set up and tearDown methon in same class with two different test.

each test will use its specific setUp and tearDown m

1条回答
  •  被撕碎了的回忆
    2021-01-29 11:45

    In the question, you mention that you have two tests, each with its own setup and teardown. There are at least two ways to go:

    You can either embed the setUp and tearDown code into each of the tests:

    class FooTest(unittest.TestCase):
        def test_0(self):
            ... # 1st setUp() code
            try:
                ... # 1st test code
            except:
                ... # 1st tearDown() code
                raise
    
        def test_1(self):
            ... # 2nd setUp() code
            try:
                ... # 2nd test code
            except:
                ... # 2nd tearDown() code
                raise
    

    Alternatively, you can split the class into two classes:

    class FooTest0(unittest.TestCase):
        @classmethod
        def setUp(cls):
            ...
    
        @classmethod
        def tearDown(cls):
            ...
    
        def test(self):
           ...
    

    The first option has fewer classes, is shorter, and more straightforsard. The second option more cleanly decouples setting up the fixture, and cleaning it up, then the test code itself. It also future proofs adding more tests.

    You should judge the tradeoffs based on your specific case, and your personal preferences.

    0 讨论(0)
提交回复
热议问题