Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In phpunit what is the difference between __construct versus setup?

Tags:

phpunit

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?

like image 532
Rahul Avatar asked Oct 07 '14 10:10

Rahul


Video Answer


2 Answers

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.

like image 77
Ian Bytchek Avatar answered Oct 06 '22 10:10

Ian Bytchek


As I have just found out, implementing the default class constructor instead of the setupBeforeClass() method breaks the @dataProvider annotations (probably all kinds of annotations), yielding a "Missing argument" exception for any parameterized tests.

Missing argument 1 for AppBundle\Tests\Service\InvitationVerifierTest::testDireccionInvalida()

Replacing public function __construct() for public static function setUpBeforeClass() gets rid of the exception. So there it goes, favor the setupBeforeClass() method over the regular constructor.

PHPUnit version 4.5.0

like image 40
Marcel Hernandez Avatar answered Oct 06 '22 11:10

Marcel Hernandez