When you are setting up a known state for tests, you have the following two options:
Set it before each test case class, runs once before and/or after each test case
Set it before each test method, runs before each test and/or after each test
The setUp()
and tearDown()
methods are the most common ones used to set a known state for tests and do clean up after the test is executed. By definition, it is called the fixture or test context—known state for tests.
The setUp()
method is called before every test is executed. Each test method has set up know state and all required settings; you don't have to duplicate the same code for similar tests.
The tearDown()
method is opposite to setUp()
, and it is called when the test finishes. For example, when working with a file, it might be placed where fclose
(closes an open file pointer) is required.