使用phpunit

在快速开发,频繁上线的项目中,代码很容易出现问题,这时候做好单元测试就非常的重要。

1. 安装

项目地址:https://github.com/sebastianbergmann/phpunit/

手动安装很麻烦,推荐使用pear直接安装

yum install php-pear.noarch

pear install phpunit/PHPUnit
pear install phpunit/PHP_Invoker
pear install phpunit/PHPUnit_Selenium
pear install phpunit/PHPUnit_Story

2. 使用

'Car',
	);

	/**
	 * 不是test开头的测试方法使用@test
	 * 
	 * @test 注解么?
	 */
	public function noTest()
	{
		$this->assertEquals(1, 1);
		$this->assertEquals(1, 1);
		return false;
	}

	/**
	 * 依赖于noTest noTest返回值是这个参数值,noTest不过,这个检查跳过
	 * 
	 * @depends noTest
	 */
	public function testCreate($return)
	{
		$this->assertFalse($return, 'failed');
	}
	
	/**
	 * 使用数据源验验证测试
	 * 
	 * @dataProvider testProvider
	 */
	public function testArry($arr)
	{
		$this->assertArrayHasKey("return", $arr);
	}
	
	public function testProvider()
	{
		return array(
			array(array('return' => 'ss')),
			array(array('return' => 'ss')),
			array(array('return' => 'ss')),
		);
	}
	
	
	public function testException()
	{
		// 期待的异常
		$this->setExpectedException('Exception');
		// 抛出异常,测试通过
		throw new Exception('test');
	}

	/**
	 * 错误异常
	 * 
	 * @expectedException PHPUnit_Framework_Error
	 */
	public function testError()
	{
		// $this->fail('test');
		// PHP错误会抛出框架内置的异常 PHPUnit_Framework_Error
		include 'nofileffa.php';
	}
	
	public function setUp()
	{
		fwrite(STDOUT, 'set up');
		$this->queue = array(1, 2, 3);
	}
	
	public function tearDown()
	{
		fwrite(STDOUT, 'tear down');
		$this->queue = null;
	}
	
	public function testFixture()
	{
		$this->assertEquals(array(1, 2, ), $this->queue);
	}
	
	public function onNotSuccessfulTest(Exception $e)
	{
		fwrite(STDOUT, 'not success');
		parent::onNotSuccessfulTest($e);
	}
}

3. 部分资料

断言:http://www.phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.assertions

fixtures:http://www.phpunit.de/manual/current/en/fixtures.html

注解:http://www.phpunit.de/manual/current/en/appendixes.annotations.html

yii test:http://www.yiiframework.com/doc/guide/1.1/zh_cn/test.overview   PHPUnit 3.7的authload换成了匿名函数,需要改一下,不然yii加载会有问题.

 

此条目发表在PHP分类目录。将固定链接加入收藏夹。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据