问题
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 objec 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 undetstand which one is good practice?
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/26234169/in-phpunit-what-is-the-difference-between-construct-versus-setup