When unittest does multiple tests, setUp is run each time the test is called. However, if the setUp process is heavy, it will take too long to execute because it is called multiple times.
So, if you want to call setUp only once, how should you write it? It is solved by defining setUpClass instead of using setUp.
The following code is given as a specific example.
test_setup.py
import unittest
class HogeTest(unittest.TestCase):
def setUp(self):
print('Called `setUp`.')
@classmethod
def setUpClass(self):
print('Called `setUpClass`.')
def test_called1(self):
self.assertTrue(True)
def test_called2(self):
self.assertTrue(True)
def test_called3(self):
self.assertTrue(True)
This code has a method that is executed when setUp
and setUpClass
are initialized. These are the methods provided by unittest respectively. Also, the method here is defined to output a character string each time it is executed. There are also three defined tests.
Now let's see if the output string does what this code expects.
Expect that the character string with setUp
is output multiple times, and that the character string with setUpClass
is output once.
Here is the result of the actual execution.
$ python3 -m unittest test_setup.py
Called `setUpClass`.
Called `setUp`.
.Called `setUp`.
.Called `setUp`.
.
----------------------------------------------------------------------
Ran 3 tests in 0.001s
OK
It was confirmed that it was working as expected.
qiita: python unit test template stackoverflow: Run setUp only once
Recommended Posts