Reputation: 9205
class TestClass extends PHPUnit_Framework_TestCase {
function testSomething() {
$class = new Class();
$this->assertTrue($class->someFunc(1));
}
function testSomethingAgain() {
$class = new Class();
$this->assertFalse($class->someFunc(0));
}
}
Hi, do I really have to create $class for every test function I create? Or is there an unknown constructor like function that I have yet to discover, since constructors don't seem to work in PHPUnit.
Thanks
Upvotes: 14
Views: 10108
Reputation: 1312
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.
Upvotes: 0
Reputation: 162801
You can use the setUp() and tearDown() methods with a private or protected variable. setUp() is called before each testXxx() method and tearDown() is called after. This gives you a clean slate to work with for each test.
class TestClass extends PHPUnit_Framework_TestCase {
private $myClass;
public function setUp() {
$this->myClass = new MyClass();
}
public function tearDown() {
$this->myClass = null;
}
public function testSomething() {
$this->assertTrue($this->myClass->someFunc(1));
}
public function testSomethingAgain() {
$this->assertFalse($this->myClass->someFunc(0));
}
}
Upvotes: 31