In phpunit what is the difference between __construct versus setup?

phpunit

Solution

`setUp()` gets called before each of your tests is ran. `__construct()` happens when your class is instantiated. So if you have multiple tests and they use local properties and modify them, using `setUp()` you can ensure that they are the same before each test is ran. The opposite of `setUp()` is `tearDown()` where you can ensure that test data gets cleaned up after each test.

Problem

I am curious to know it is good practice to create object in test class __construct or we should always use setup/teardown approach ( or setUpBeforeClass/tearDownAfterClass approach)? I aware of the fact set/teardown gets called for each test so will it do any good if I put my object creation code in it? e.g. //mytestclass.php ``` class MyTestClass extends PHPUnit_Framework_TestCase { private $obj; protected function setUp() { $this->obj = new FooClass(); } public testFooObj() { //assertions for $this->obj } ... } ``` what could be the issues if I create object in constructor like this: ``` class MyTestClass extends PHPUnit_Framework_TestCase { private $obj; protected function __construct() { $this->obj = new FooClass(); } public testFooObj() { //assertions for $this->obj } ... } ``` I tried googling around as well as PHPUnit documentation couldn't get much information about, Can you please help me to understand which one is good practice?

Original source