LoginSignup
13
9

More than 5 years have passed since last update.

CakePHP3でShellのテストをする

Posted at

bakeでShellのテストファイルを作れますが、それ以外に書いてあるものがあんまりないので、少し書こうと思います。

一応参考:
Cakebook 3.x Shells, Tasks & Console Tools
Cakebook 3.x Testing

実行のテストをする

Shellの実行は、runCommand()でテストできます。
getOptionParser()で記述した引数オプション付きの実行もこれでテストできます。

HogeShellTest.php
public function setUp()
{
    parent::setUp();
    $this->io = $this->getMock('Cake\Console\ConsoleIo');
    $this->Hoge = new HogeShell($this->io);
}

public function testTypeOption()
{
    $this->Hoge->initialize();
    $this->Hoge->runCommand(['--type', 'type1']);
}

なお、initialize()も書かないと勝手には実行されないので、setUp()に書くか、initialize()内の処理のテストも書きたい場合は各テストに毎回書く必要があります。

abortをテストする

Shellの実行を、エラーなどの理由で途中で終わらせたい場合は、$this->abort()を使います。(CakePHP3.2から追加されました。3.1までは$this->error()でした。)
このabort()が実行されているかをテストしたい場合は、abort()はStopExceptionの例外を投げるので、setExpectedException()を使います。

HogeShellTest.php
public function testAbort()
{
    $this->Hoge->initialize();
    $this->setExpectedException('Cake\Console\Exception\StopException');
    $this->Hoge->runCommand([]);
}

CakePHP2の時は、$this->setExpectedException('StopException')と書けば良かったのですが、3だとCake\Console\Exception\から書かないとダメみたいです。

13
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
9