LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 5 years have passed since last update.

【CakePHP3】PHPUnitを使った単体試験

Posted at

前提事項としてプロジェクト配下に、composer.pharが存在すること。

Windows環境で無い場合、以下コマンド実行でComposerを取得可能。

php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));"

以下コマンドを実行して、CakePHP3プロジェクト中にPHPUnitを導入。

//Composer経由でPHPUnitインストール
php composer.phar require --dev phpunit/phpunit:"^5.7|^6.0"

//CakePHP3.4.1よりも前の場合
php composer.phar require --dev phpunit/phpunit:"<6.0"

以下コマンドでPHPUnitが実行可能か確認。

vendor/bin/phpunit

//実行結果
PHPUnit 4.8.35 by Sebastian Bergmann and contributors.

......

Time: 4.12 seconds, Memory: 13.00MB

OK (6 tests, 34 assertions)

上記のような実行結果が表示されれば、PHPUnitは利用可能。

ControllerでのPHPUnit

bakeコマンドでControllerクラスを作成すると、Testクラスも自動生成。

//Windowsでの実行時は[/]を[\]に置き換える
bin/cake bake controller XXX

//SampleController.phpを作る
bin/cake bake controller Sample

画面上に適当な文字(Hello World)が表示されるようにviewを用意。

view表示が可能かどうかテスト

view上に[Hello World]が表示されているか確認。

尚、routesはDocumentRoot/sample。

namespace App\Test\TestCase\Controller;

use Cake\TestSuite\IntegrationTestCase;

/**
 * App\Controller\SampleController Test Case
 */
class SampleControllerTest extends IntegrationTestCase
{
    public function testIndex()
    {
        $this->get('/sample');
        $this->assertResponseOk();
        $this->assertTemplate('index');
        $this->assertResponseContains('Hello World');
    }   
}

12行目でGETリクエストを投げ、指定メソッドを呼び出し。

13行目でレスポンスコードが2xxであるかチェック。

14行目で指定のテンプレートが呼び出されたかチェック。

15行目でレスポンス内容に[Hello World]が含まれているかチェック。

view表示が不可能であることのテスト

アクセスNG画面にアクセスできないことを確認する時など利用。

class SampleControllerTest extends IntegrationTestCase
{
    public function testIndex()
    {
        $this->get('/sample');
        // 5xx レスポンスコードをチェック
        $this->assertResponseFailure();
    }

}

例外など起きると、レスポンスに500系が返ってきます。

ShellでのPHPUnit

bakeコマンドでShellクラスを作成すると、Testクラスも自動生成。

ただし公式ページでもコンソール試験は紹介されてないので、やる必要ないかも…

class SampleShellTest extends TestCase
{

    public $io;
    public $Sample;

    public function setUp()
    {
        parent::setUp();
        $this->io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();
        $this->Sample = new SampleShell($this->io);
    }

    public function tearDown()
    {
        unset($this->Sample);
        parent::tearDown();
    }

    public function testIndex()
    {
        $this->Sample->runCommand([]);
    }
}

一応runCommandでコンソール実行させることが出来ます。

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