LoginSignup
7
4

More than 5 years have passed since last update.

初めてのTDD(PHPUnit)

Last updated at Posted at 2017-08-17

チーム内でTDDの布教をした際に使用した資料

単体テストのすゝめ

TDDとは?

テスト駆動開発 (てすとくどうかいはつ、test-driven development; TDD) とは、プログラム開発手法の一種で、プログラムに必要な各機能について、最初にテストを書き(これをテストファーストと言う)、そのテストが動作する必要最低限な実装をとりあえず行った後、コードを洗練させる、という短い工程を繰り返すスタイルである。(wikipedia)
まず、テストコードを書く。当然失敗するので、それが通るようにするのをひたすら繰り返す。

サンプルコード

BDDのテストフレームワークが潮流してきていますが、今回はオーソドックスにPHPUnitを使います。
ライブラリ及びコードを同じフォルダに突っ込んでおく。

PHPUnit
https://phpunit.de/
上記から実行するphpのバージョンに対応するphpUnitをダウンロードする。
下記サンプルコードはphp7で実行してるのでPHPUnit 6.3をダウンロード。
(とはいえ、下記コードならある程度古いバージョンでも動くと思いますが)

SampleTest.php
<?php
use PHPUnit\Framework\TestCase;
require_once("SampleProgram.php");

class SampleTest extends TestCase
{
    // まずはうまく返せてるか
    public function testReturn()
    {
        $sample = new SampleProgram();
        $this->assertEquals($sample->step1(12345), 12345);
    }

    // 文字数を確認する
    public function testCharNumber()
    {
        $sample = new SampleProgram();
        $this->assertEquals($sample->step2(12345), 5);
    }

    // 計算してみる
    public function testCalculation()
    {
        $sample = new SampleProgram();
        $this->assertEquals($sample->step3(12345), 15);
    }

    // 予期しない入力値を制御できるか
    /**
     * @expectedException        Exception
     * @expectedExceptionMessage 二桁の自然数ではないです
     */
    public function testErrorHandle()
    {
        $sample = new SampleProgram();
        $this->assertEquals($sample->step4(12345), 15);
        $sample->step4('aiueo');
    }
}
?>
SampleProgram.php
<?php
use PHPUnit\Framework\TestCase;

class SampleProgram
{
    public function step1($arg)
    {
        return $arg;
    }

    public function step2($arg)
    {
        return strlen($arg);
    }

    public function step3($arg)
    {
        $total = 0;
        for($i = 0; $i < strlen($arg); $i++){
            $total += substr($arg, $i, 1);
        }
        return $total;
    }

    public function step4($arg)
    {
        if(preg_match('/[0-9]{2,}/', $arg))
        {
            throw new Exception("二桁の自然数ではないです");
        }
        $total = 0;
        for($i = 0; $i < strlen($arg); $i++){
            $total += substr($arg, $i, 1);
        }
        return $total;
    }
}
?>

実行コード(例)
php phpunit-6.2.phar SampleTest.php

7
4
2

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
7
4