When should I use setUpClass and when __init__?

后端 未结 1 1190
闹比i
闹比i 2021-02-08 08:49

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 set

相关标签:
1条回答
  • 2021-02-08 09:23

    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 you 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.

    0 讨论(0)
提交回复
热议问题