slimでphpunit使用してユニットテスト

今回はphpunitをインストールした上で、ユニットテストを行う手順を記します。
ユニットテストはメソッド単体だったりの小さい粒度のテストで
今回はsrc/Taka512/Services/NameService.phpのgetNameメソッドをテストします。
サービスクラスは以下のような感じでコンテナに登録しているとします。

$container['app.services.name_service'] = $container->share(function ($c) {
    return new \Taka512\Services\NameService($c);
});

まずアプリケーション側をテストしやすい形に作り替えます。
具体的にはindex.phpで行っていたコンテナ作成処理等をbootstrap.phpに移動します。

web/index.php

<?php
define('ENVIRONMENT', 'prod');
require '../config/bootstrap.php';

$container = createContainer();
$app = $container['app'];
require PROJECT_DIR.'/config/routes.php';
$app->run();

config/bootstrap.php

<?php
define('PROJECT_DIR', dirname(__FILE__) . '/..');
require PROJECT_DIR . '/vendor/autoload.php';

function createContainer()
{
    require PROJECT_DIR . '/config/config.php';
    $container = new \Pimple();
    $container['app'] = new \Slim\Slim($config);

    require PROJECT_DIR . '/config/parameters.php';
    require PROJECT_DIR . '/config/databases.php';
    require PROJECT_DIR . '/config/services.php';

    return $container;
}

phpunitのインストール

composerでインストールするとvendor/binの下にphpunitがインストールされます。

$ vi composer.json
    "require": {
        "slim/slim":       "2.*",
        "slim/extras":     "2.0.*",
        "twig/twig":       "1.*",
        "pimple/pimple":   "v1.0.2",
        "phpunit/phpunit": "3.7.21",
    },
$ php composer.phar update
$ ls vendor/bin/phpunit
vendor/bin/phpunit

テストの設定ファイルを作る

ユニットテスト用の設定ファイルをconfigの下に作成します。
先ほど作成したbootstrapを読み込んで「tests/unit」下のテストを起動する設定となります。

$ vi config/unit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap = "bootstrap.php" >
    <testsuites>
        <testsuite name="unit test">
            <directory>../tests/unit</directory>
        </testsuite>
    </testsuites>
</phpunit>

テスト作成

テストディレクトリを掘ってテストファイルを作成します。

$ mkdir -p test/unit/Services
$ vi tests/unit/Services/NameServiceTest.php
<?php
namespace Taka512\Services;

class NameServiceTest extends \PHPUnit_Framework_TestCase
{
    public function testGetName()
    {
        \Slim\Environment::mock();
        $container = createContainer();
        $name = $container['app.services.name_service']->getName();
        $this->assertEquals($name, 'hoge');
    }
}


テスト実行

設定ファイルを指定してphpunitを実行するとサービスクラスのテストができましたとさ!

$ vendor/bin/phpunit -c config/unit.xml
PHPUnit 3.7.21 by Sebastian Bergmann.

Configuration read from /home/coh2/config/unit.xml

.

Time: 0 seconds, Memory: 5.00Mb

OK (1 test, 1 assertion)