LoginSignup
1
1

More than 5 years have passed since last update.

PHPUnit とりあえず動かすとこまで

Posted at

phpunitのインストール

  • composer.json
composer.json
{
    "require-dev": {
        "phpunit/phpunit": "*"
    }
}
  • インストール
$./composer.phar install

ディレクトリの作成

$ mkdir src
$ mkdir tests

テスト対象ソースをautoloadするように設定する

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

    "autoload": {
        "psr-4": {
            "Sample\\": "src/"
        }
    }

}

実装

  • テストコード
tests/SampleTest.php
<?php

require_once('vendor/autoload.php');

class SampleTest extends PHPUnit\Framework\TestCase {

    public function test_add() {
        $sample = new Sample\Sample();
        $this->assertEquals(10, $sample->Add(4, 6));
    }

    public function test_sub() {
        $sample = new Sample\Sample();
        $this->assertEquals(1, $sample->Sub(7, 6));
    }

}
  • テスト対象コード
src/Sample.php
<?php

namespace Sample;

class Sample {

    // $a + $b を返す                                                                                                                                                                                                                                                           
    public function add($a, $b) {
        return $a + $b;
    }

    // $a - $b を返す                                                                                                                                                                                                                                                           
    public function sub($a, $b) {
        return $a - $b;
    }

}

テスト実行

$ vendor/bin/phpunit tests/
PHPUnit 7.1.4 by Sebastian Bergmann and contributors.

..                                                                  2 / 2 (100%)

Time: 21 ms, Memory: 4.00MB

OK (2 tests, 2 assertions)
1
1
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
1
1