我使用的是Zendstudio,直接配有PHPunit了,只在在要测试的项目加入PHPUnit的包就可以使用PHPUnit进行单元测试了。
为了演示PHPunit的使用,我写了一个测试类Demo
class Demo{
public function sum($a,$b){
return $a+$b;
}
public function subtract($a,$b){
return $a-$b;
}
}
然后 在将包直接放到项目目录下
新建一个Demotest类,
可以直接使用zendstudio的新建类PHPUnit Test Case
然后 里面有写好部分测试用的代码 ,
写入要测试的方法,
我在Demo要测试加法和减法,
第一步,引入PHP文件
require_once 'Demo.php';
require_once 'PHPUnit/Framework.php';
原本就有代码,
/**
* test case.
*/
class DemoTest extends PHPUnit_Framework_TestCase {
/**
* Prepares the environment before running a test.
*/
protected function setUp() {
parent::setUp ();
// TODO Auto-generated DemoTest::setUp()
}
/**
* Cleans up the environment after running a test.
*/
protected function tearDown() {
// TODO Auto-generated DemoTest::tearDown()
parent::tearDown ();
}
/**
* Constructs the test case.
*/
public function __construct() {
// TODO Auto-generated constructor
}
}
添加上测试方法
public function testSum(){
$demo=new Demo();
$this->assertEquals(4,$demo->sum(2,2));
}
public function testSubstract(){
$demo=new Demo();
$this->assertNotEquals(3,$demo->subtract(1,1));
}
在Run运行PHPunit Test,
运行成功,会显示绿色 为了使用PHPunit更方便,
将$demo=new Demo();放在setUp()里,
$this->demo=new Demo();
这里在测试方法里面就可简写成这样了,
public function testSum(){
$this->assertEquals(4,$this->$demo->sum(2,2));
}
public function testSubstract(){
$this->assertNotEquals(3,$this->$demo->subtract(1,1));
}
这样,PHPUnit的简单入门就完了。