Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use setUpClass and when __init__?

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?

like image 868
Nakilon Avatar asked Aug 05 '13 10:08

Nakilon


People also ask

What is the difference between setUp tearDown and setUpClass tearDownClass?

setUpClass and tearDownClass are run once for the whole class; setUp and tearDown are run before and after each test method.

What is setUpClass?

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): ...

What is the use of setUp () method in test case class?

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.


1 Answers

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.

like image 163
Martijn Pieters Avatar answered Sep 24 '22 11:09

Martijn Pieters