In PHPUnit testing we have the setUp() method that is called before every test. And we have the tearDown() method that is called after every test.
setUp() is used to initialise variables, open file connection etc.
tearDown() is used to unset variables, close file connection etc.
Example: Testing Odd/Even number
use PHPUnit\Framework\TestCase;
class OddEvenTest extends TestCase
{
private $number;
protected function setUp()
{
$this->number = 2;
}
public function testOdd()
{
$this->number++;
$this->assertNotEquals(0, $this->number % 2);
}
public function testEven()
{
$this->assertEquals(0, $this->number % 2);
}
protected function tearDown()
{
$this->number = null;
}
}
By running tests of the above class.
Output:
Method: OddEvenTest::setUp
Method: OddEvenTest::testOdd
Method: OddEvenTest::tearDown
Method: OddEvenTest::setUp
Method: OddEvenTest::testEven
Method: OddEvenTest::tearDown
Bonus:
It happens that we have some settings to be shared all tests, for example, it is wise to get the database connection initialized only once in the begining of the tests rather than get connection multiple times in the setUp() method!
For that pupose we use the setUpBeforeClass() method which is called before the first test is executed and the tearDownAfterClass() method which is called after last test is executed.
So, basically we create a database connection only once and then reuse the connection in every test. This helps to run the test faster.