phpunit之Annotations

4 篇文章 0 订阅
4 篇文章 0 订阅

phpunit中的Annotations

如果有其他编程语言(如java)经验的开发者,应该对Annotations(注解)不陌生,其实在phpunit中,一个简单的如下面的一段注释也可以认为是Annotations:

<? php
class MyTestClass extends PHPUnit_Framework_TestCase
{
/* *
* Testing the answer to “do you love unit tests?”
*/
public function testDoYouLoveUnitTests()
{
$love = true ;
$this -> assertTrue( $love );
}
}
?>

   可以看到,其实一段以/** **/为标记的文字,就可以认为是一种Annotations,但Annotations其实不单单是简单的注释,它是与一个程序元素相关联信息或者元数据的标注,它不影响程序的运行,但相关的软件工具或框架能够将其转换成特殊的元数据标记,以方便开发者以更少的代码去提高效率(比如通过。如果你熟悉Java,则会发现在Java SE 5中及象Spring等框架中,都大量使用了Annotations。

  然而,由于php并不象Java那样是编译性语言,因此本身缺乏去解析Annotations的机制,但幸好phpunit去提供了这样的功能,我们以下面的代码为例:

<? php
class MyMathClass
{

public function addValues( $a , $b )
{
return $a + $b ;
}
}
?>

   上面的只是一个简单的加法的例子,为此,我们使用Annotations去编写一个单元测试,在上两篇文章中,我们采用的是手工编写单元测试的方法,而本文中,将介绍使用phpunit命令行的方法,自动生成单元测试的框架,方法如下:

  首先把上面的类保存为MyMathClass.php,然后在命令行下运行如下命令:

phpunit –skeleton - test MyMathClass

   这时phpunit会自动生成如下的框架单元测试代码:

<? php
require_once ' /MyMathClass.php ' ;

class MyMathClassTest extends PHPUnit_Framework_TestCase
{
/* *
* @var MyMathClass
*/
protected $object ;
/* *
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this -> object = new MyMathClass;
}
/* *
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
}
/* *
* @todo Implement testAddValues().
*/
public function testAddValues()
{
// Remove the following lines when you implement this test.
$this -> markTestIncomplete(
' This test has not been implemented yet. '
);
}
}
?>

   可以看到,phpunit为我们生成的单元测试代码自动引入了原来的MyMathClass.php,同时也生成了setUp和tearDown方法,但唯一的核心单元测试代码是留给了我们编写。如果想在这个基础上更快速的生成我们想要的单元测试代码,要如何实现呢?没错,就是使用annotations!我们可以在原来的MyMathClass.php中加入如下的annotations。

<? php
class MyMathClass
{
/* *
* Add two given values together and return sum
* @assert (1,2) == 3
*/
public function addValues( $a , $b )
{
return $a + $b ;
}
}
?>

  然后再象上述一样在命令行运行:

  phpunit –skeleton - test MyMathClass

  这个时候会为我们生成如下的单元测试代码:

<? php
/* *
* Generated from @assert (1,2) == 3.
*/
public function testAddValues()
{
$this -> assertEquals(
3 ,
$this -> object -> addValues( 1 , 2 )
);
}
?>

  看到了么?我们在原有的类中加入了注解@assert(1,2)==3,则phpunit自动为我们生成了正确的单元测试代码。当然,可以参考phpunit手册,学习到更多的关于@assert注解使用的规则。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值