CakePHP shell单元测试

时间:2012-09-18 15:57:04

标签: php unit-testing cakephp cakephp-2.0

我想为我正在创建的CakePHP shell编写单元测试,但testing documentation中没有提到它们或者烘焙:

---------------------------------------------------------------
Bake Tests
Path: /home/brad/sites/farmlogs/app/Test/
---------------------------------------------------------------
---------------------------------------------------------------
Select an object type:
---------------------------------------------------------------
1. Model
2. Controller
3. Component
4. Behavior
5. Helper
Enter the type of object to bake a test for or (q)uit (1/2/3/4/5/q) 

由于CakePHP似乎没有默认的shell测试设置,我的基本shell测试的结构应该是什么样的?

2 个答案:

答案 0 :(得分:6)

根据Mark Story的AssetCompress和CakeDC的Migrations中的示例判断,只是模仿其他测试的目录结构:

Test/
  Case/
    Console/
      Command/
        Task/
          MyShellTaskTest.php
        MyShellTest.php

您的测试只需扩展CakeTestCase对象,就像任何其他通用测试一样:

class MyShellTest extends CakeTestCase {
}

如果需要,您可以覆盖基本shell,就像使用Controller测试一样:

class TestMyShell extends MyShell {
}

没有什么特别的,只要坚持惯例。

答案 1 :(得分:0)

我认为app / lib / lib / Cake / Console / Command / TestShellTest.php可以作为参考。

1,在app / Test / Case / Console / Command / yourfile.php中创建文件,使用App::uses('your class', 'relative path').说明您的课程 例如:

App::uses('yourShellClass', 'Console/Command');
App::uses('ShellDispatcher', 'Console');
App::uses('Shell', 'Console');

2,从shell类A中编写一个模拟类B,其函数使用数据在类A中返回。 例如:

 class TestYourShellClass extends YourShellClass {
         public function F1 ($parms){
               //if you need use database here, you can 
               //$this->yourModel = ClassRegistry::init('yourModel');
               return $this->_F1($parms);      
         }

    }

3,编写A类测试类,需要在启动时初始化它。 例如:

 class YourShellClassTest extends CakeTestCase {
        public function setUp()
        {
            parent::setUp();
            $out = $this->getMock('ConsoleOutput', [], [], '', false);
            $in = $this->getMock('ConsoleInput', [], [], '', false);
            $this->Shell = $this->getMock(
                // this is your class B, which mocks class A.
                'TestYourShellClass',
                ['in', 'out', 'hr', 'help', 'error', 'err', '_stop', 'initialize', '_run', 'clear'],
                [$out, $out, $in]
            );
            $this->Shell->OptionParser = $this->getMock('ConsoleOptionParser', [], [null, false]);
        }

        /**
         *  tear down method.
         *  
         *  @return void
         */
        public function tearDown()
        {
            parent::tearDown();
            unset($this->Dispatch, $this->Shell);
        }       
   }

4,测试功能可以是这样的。

 /**
 *  test _F1.
 *  
 *  @return void
 */
public function testF1()
{
    $this->Shell->startup();
    $return = $this->Shell->F1();
    $expectedSellerCount = 14;
    $this->assertSame($expectedSellerCount, $return);
}

然后您可以在http://yourdomain/test.php

中查看结果