PHPUnit单元测试入门

本文介绍了如何在ZendStudio中使用PHPUnit进行单元测试。通过创建一个简单的数学运算类及其测试用例,展示了PHPUnit的基本用法。

  我使用的是Zendstudio,直接配有PHPunit了,只在在要测试的项目加入PHPUnit的包就可以使用PHPUnit进行单元测试了。

 

为了演示PHPunit的使用,我写了一个测试类Demo

class Demo{
   public function sum($a,$b){
   	  return $a+$b;
   	
   }
   public function subtract($a,$b){
   	  return $a-$b;
   	
   }
}

 

然后 在将包直接放到项目目录下2010051921072542.jpg

新建一个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,
运行成功,会显示绿色 2010052111011421.jpg 为了使用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的简单入门就完了。


转载于:https://www.cnblogs.com/ScriptZhang/archive/2010/05/19/1739572.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值