What is the difference between setUp()
and setUpClass()
in the Python unittest
framework? Why would setup be handled in one method over the other?
I want to understand what part of setup is done in the setUp()
and setUpClass()
functions, as well as with tearDown()
and tearDownClass()
.
The difference manifests itself when you have more than one test method in your class.
setUpClass
andtearDownClass
are run once for the whole class;setUp
andtearDown
are run before and after each test method.For example:
When you run this test, it prints:
(The dots (
.
) areunittest
's default output when a test passes.) Observe thatsetUp
andtearDown
appear before and aftertest1
andtest2
respectively, whereassetUpClass
andtearDownClass
appear only once, at the beginning and end of the whole test case.After reading both question and the accepted answer, I think some supplement can be made.
Q: Why would setup be handled in one method over the other?
A: It's because the test method may need preliminary and the preliminary varies from test method to test method.
For example, take below code from https://www.tutorialspoint.com/unittest_framework/unittest_framework_api.htm as a sample:
The method
testadd
andtestsub
needs different input and we can set the value of the input respectively insetUp
method.