Python unittest setUp function
python
Solution
- setUp() and tearDown() methods are automatically used when they are available in your classes inheriting from unittest.TestCase.
- They should be named setUp() and tearDown(), only those are used when test methods are executed.
Example:
class MyTestCase(unittest.TestCase):
def setUp(self):
self.setUpMyStuff()
def tearDown(self):
self.tearDownMyStuff()
class TestSpam(MyTestCase):
def setUpMyStuff(self):
# called before execution of every method named test_...
self.cnx = # ... connect to database
def tearDownMyStuff(self):
# called after execution of every method named test_...
self.cnx.close()
def test_get_data(self):
cur = self.cnx.cursor()
...
Problem
I am relatively new to Python. According to unittest.setUp documentation: setUp() Method called to prepare the test fixture. This is called immediately before calling the test method; any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing. My question about `setUp` is as follows: In our testing code base, I have seen that we customized the Python testing framework by inheriting from `unittest.TestCase`. Originally, `unittest.TestCase` has names `setUp` and `tearDown`.In the customized class, we have `setUpTestCase` and `tearDownTestCase`. So each time those two functions will be called instead of those original counterparts. My questions are: - How are those `setUp` and `tearDown` functions being called by the underlying test runner? - Is it required that those functions used to set up test cases should start with `setUp` and functions used to tear down test cases should start with `tearDown`? Or it can be named as any valid identifier? Thank you.