LoginSignup
21
25

More than 5 years have passed since last update.

Symfony2 + PHPUnitではじめてのテスト(単体テスト編)

Posted at

まずは導入してみよう

なぜ、テストコードを書くのか、テストコードはどう書くべきか、といった話はおいといて、今回はとにかくテストコードを書いて実行してみるということを目的とします。

PHPUnitのインストール(composer)

さっそくインストールからはじめましょう。
今回はタイトルにもあるようにSymfony2(2.3)環境にPHPUnit(3.7)を導入します。
composer.jsonに下記記述を追加し、updateすれば、インストールは完了です。

第3章 PHPUnit のインストール - phpunit

composer.json
{
    "require-dev": {
        "phpunit/phpunit": "3.7.*"
    }
}

さっそくやってみよう

はじめにこれを読みましょう。

ユニットテスト

下記のようなシンプルなクラスがあるとします。
年月を指定して、月初もしくは月末を取得するだけのクラスですが、実際に使う前に単体である何パターンかテストしておきたいところです。

DateTimeHelper.php
<?php
namespace Sopra\CoreBundle\Helper;
use DateTime;

class DateTimeHelper {

    private function __construct() {  }

    public static function getFirstDayInMonth($year, $month)
    {

        return new DateTime("$year-$month-01");
    }

    public static function getLastDayInMonth($year, $month) {

        return new DateTime(date('Y-m-d', mktime(0,0,0, $month + 1, 0, $year)));
    }
}

そこで、下記のようなテストケースを作成します。

DateTimeHelperTest.php
<?php
namespace Sopra\CoreBundle\Tests\Helper;

use Sopra\CoreBundle\Helper\DateTimeHelper;
use Sopra\CoreBundle\Tests\TestCase\BaseTestCase;

class DateTimeHelperTest extends BaseTestCase {

    public function testGetFirstDayInMonth() {

        $firstDay = DateTimeHelper::getFirstDayInMonth(2013, 1);
        $this->assertEquals('2013-01-01', $firstDay->format('Y-m-d'));

        $firstDay = DateTimeHelper::getFirstDayInMonth(2013, 12);
        $this->assertEquals('2013-12-01', $firstDay->format('Y-m-d'));

        $firstDay = DateTimeHelper::getFirstDayInMonth(2014, 3);
        $this->assertEquals('2014-03-01', $firstDay->format('Y-m-d'));
    }

    public function testGetLastDayInMonth() {

        $lastDay = DateTimeHelper::getLastDayInMonth(2012, 2);
        $this->assertEquals('2012-02-29', $lastDay->format('Y-m-d'));

        $lastDay = DateTimeHelper::getLastDayInMonth(2013, 2);
        $this->assertEquals('2013-02-28', $lastDay->format('Y-m-d'));

        $lastDay = DateTimeHelper::getLastDayInMonth(2013, 12);
        $this->assertEquals('2013-12-31', $lastDay->format('Y-m-d'));
    }
}

テストの実行

作成したテストを実行するために、phpunitコマンドを実行します。
phpunitコマンドについては、本家サイトに詳しい説明がありますので参照ください。

コマンドラインのテストランナー - PHPUnit

実際に上述のDateTimeHelperTestを実行してみると、下記のように出力されます。

$ cd bin
$ ./phpunit -c ../app/ ../{path to test file}/DateTimeHelperTest.php
PHPUnit 3.7.27 by Sebastian Bergmann.

Configuration read from /path/to/Application Root/app/phpunit.xml

..

Time: 353 ms, Memory: 16.25Mb

OK (2 tests, 6 assertions)
21
25
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
21
25