Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup or construct a PHP Unit test

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

like image 310
lemon Avatar asked Oct 02 '09 01:10

lemon


People also ask

How do you construct unit test?

To get started, select a method, a type, or a namespace in the code editor in the project you want to test, right-click, and then choose Create Unit Tests. The Create Unit Tests dialog opens where you can configure how you want the tests to be created.

How do I run a test case in PHP?

From the Menu-bar, select Run | Run As | PHPUnit Test . To debug the PHPUnit Test Case, click the arrow next to the debug button on the toolbar, and select Debug As | PHPUnit Test . From the Main Menu, select Run | Debug As | PHPUnit Test . The unit test will be run and a PHP Unit view will open.

What are PHP tests?

PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks.


1 Answers

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));
 }
}
like image 82
Asaph Avatar answered Sep 30 '22 19:09

Asaph