When should I use setUpClass and when __init__?

oop, python, unit-testing

Solution

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.

Problem

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?

Original source