How To Specify Test Specific Setup And Teardown In Python Unittest
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 method in py
Solution 1:
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:
classFooTest(unittest.TestCase):
deftest_0(self):
... # 1st setUp() codetry:
... # 1st test codeexcept:
... # 1st tearDown() coderaisedeftest_1(self):
... # 2nd setUp() codetry:
... # 2nd test codeexcept:
... # 2nd tearDown() coderaise
Alternatively, you can split the class into two classes:
classFooTest0(unittest.TestCase):@classmethoddefsetUp(cls):
...
@classmethoddeftearDown(cls):
...
deftest(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.
Post a Comment for "How To Specify Test Specific Setup And Teardown In Python Unittest"