Is there any runtime-logic difference between these two methods? Or any behviour differences?
If not, then should I forget about __init__
and use only setUpClass
thinking here about unittests classes like about namespaces instead of language OOP paradigm?
setUpClass and tearDownClass are run once for the whole class; setUp and tearDown are run before and after each test method.
setUpClass () A class method called before tests in an individual class are run. setUpClass is called with the class as the only argument and must be decorated as a classmethod() : @classmethod def setUpClass(cls): ...
Test setup methods enable you to create common test data easily and efficiently. By setting up records once for the class, you don't need to re-create records for each test method.
The two are quite different.
setUpClass
is a class method, for one, so it'll only let you set class attributes.
They are also called at different times. The test runner creates a new instance for every test. If your test class contains 5 test methods, 5 instances are created and __init__
is called 5 times.
setUpClass
is normally called only once. (If you shuffle up test ordering and test methods from different classes are intermingled, setUpClass
can be called multiple times, use tearDownClass
to clean up properly and that won't be a problem).
Also, a test runner usually creates all test instances at the start of the test run; this is normally cheap, as test instances don't hold (much) state so won't take up much memory.
As a rule of thumb, you should not use __init__
at all. Use setUpClass
to create state shared between all the tests, and use setUp
to create per-test state. setUp
is called just before a test is run, so you can avoid building up a lot of memory-intensive state until it is needed for a test, and not before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With