LoginSignup
12
10

More than 3 years have passed since last update.

[PHPUnit]10分でできる!はじめてのPHPUnit

Posted at

はじめてPHPのテスティングフレームワークであるPHPUnit使ったので、覚え書き。
本手順では、Composerではなく、Pharを使います。
インストールから、サンプルコードを使ったテスト実行まで、10分あればできちゃいます♪

環境

  • OS: Amazon Linux2
  • PHP: PHP 7.4.15
  • PHPUnit: 9.5.2

※PHPUnit9.5を使うには、PHPのバージョンが7.3以上である必要があります。

インストール

(1) まず、以下のコマンドを実行し、phpunit-9.5.pharをダウンロード。

$ wget https://phar.phpunit.de/phpunit-9.5.phar

(2) 実行権限を付与します。

$ chmod +x phpunit-9.5.phar

(3) バージョン確認

$ php phpunit-9.5.phar --version
PHPUnit 9.5.2 by Sebastian Bergmann and contributors.

(4) ファイル名をリネームします

$ mv phpunit-9.5.phar phpunit

(5) Pathを確認し、優先順位が最も高いPathを確認します。

$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/ec2-user/.local/bin:/home/ec2-user/bin

一番左に表示されているPathが最も優先順位が高いです。
上記の場合は、/usr/local/binですね。

(6) (5)で確認したPathに、phpunitファイルを移動させます。

$ mv phpunit /usr/local/bin/

(7) 以下のコマンドを実行して、phpunitのバージョンが出力されればOK。

$ phpunit --version
PHPUnit 9.5.2 by Sebastian Bergmann and contributors.

サンプルコードでLet'sテスト

(1) 任意のディレクトリで、テストコードstackTest.phpを作成します。

stackTest.php
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;

final class StackTest extends TestCase
{
    public function testPushAndPop(): void
    {
        $stack = [];
        $this->assertSame(0, count($stack));

        array_push($stack, 'foo');
        $this->assertSame('foo', $stack[count($stack)-1]);
        $this->assertSame(1, count($stack));

        $this->assertSame('foo', array_pop($stack));
        $this->assertSame(0, count($stack));
    }
}

このコードは、公式ドキュメントの
2. Writing Tests for PHPUnit | PHPUnit 9.5 Manual
より、拝借しました。

(2) テスト実行してみます。

$ phpunit stackTest.php
PHPUnit 9.5.2 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 00:00, Memory: 18.00 MB

OK (1 test, 5 assertions)

うまくいきました!

参考

12
10
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
12
10