Symfony2 (4) - atoum进行单元测试

文章转自 Zhipeng JIANG 的博客, http://jesusjzp.github.io/blog/2013/08/21/symfony2-test/

测试示例

先上一段代码,然后再讲讲具体代码做了什么。

  
  
  1. <?php
  2.  
  3. use atoum\AtoumBundle\Test\Controller;
  4.  
  5. /******************************************
  6. * ATOUM TESTS
  7. * To run them :
  8. * cd /path/to/the/project/
  9. * php app/console atoum BundleName
  10. *****************************************/
  11.  
  12. class FolderController extends Controller\ControllerTest
  13. {
  14.  
  15. private $userName = "unknown";
  16.  
  17. public function setUp()
  18. {
  19. // delete all the data stored in Mongo for this test
  20. }
  21.  
  22. public function beforeTestMethod($testMethod)
  23. {
  24. // do something before each test method
  25. }
  26.  
  27. public function testFolderCanBeCreated()
  28. {
  29. $client = $this->createClient();
  30. $client->request('POST', '/folders', array('title' => $title, 'abstract' => $abstract, 'idp' => ''));
  31. $response = $client->getResponse();
  32.  
  33. $this->integer($response->getStatusCode())
  34. ->isEqualTo(200)
  35. ->string($response->headers->get('Content-Type'))
  36. ->isEqualTo('application/json');
  37.  
  38. $json = json_decode($response->getContent(), true)[0];
  39. // var_dump($json);
  40. $this->string($json['title'])->isEqualTo($title);
  41. $this->string($json['abstract'])->isEqualTo($abstract);
  42. $this->string($json['owner'])->isEqualTo($this->userName);
  43. }
  • usenamespace这两个部分根据实际情况自己决定,注意,use atoum\AtoumBundle\Test\Controller;是一定要添加的。

  • extends Controller\ControllerTest不要忘记添加,这里包含了所有的断言语句的实现。

  • 跟一般的测试工具类似,这里也包括了setUp()函数和tearDown()函数,注意,这两个函数不是必须的。在atoum里,还有一个是beforeTestMethod()afterTestMethod()函数,同样,这两个函数也不是必须的,但他们的功能与之前两个不同。一般的测试流程如下:

      setUp()
    
      beforeTestMethod()
      testXXXXXXXX()
      afterTestMethod()
    
      beforeTestMethod()
      testYYYYYYYY()
      afterTestMethod()
    
      ...
    
      tearDown()
  • 在具体的测试函数里,首先需要create一个client出来,用来给api发送request,一般的request分成四种,分别是GETPOSTPUTDELETE,分别对应了查增改删。

  • 在request函数中,第二个参数是api的route,第三个参数是api需要传入的参数,用array传进去。

  • atoum的断言语句比较多,这里通常用到的有以下几个:

  
  
  1. // 判断整数值知否相等,大于,大于等于,...
  2. $this->integer($a)->isEqualTo($b);
  3. $this->integer($a)->isGreaterThan($b);
  4.  
  5. // 判断字符串是否相等
  6. $this->string($a)->isEqualTo($b);
  7.  
  8. // 判断布尔值
  9. $this->boolean($a)->isTrue();
  10. $this->boolean($a)->isFalse();
关于 symfony2的更多博客请参考 :



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值