LoginSignup
41
29

More than 3 years have passed since last update.

Laravelパッケージ開発ハンズオン〜テスト導入編〜

Posted at

前回の Laravelパッケージ開発ハンズオン〜環境編〜 続きの記事です。

Laravelテスト導入

  • sebastianbergmann/phpunit
    • PHPの単体テストフレームワーク
  • orchestral/testbench
    • Laravelのパッケージ開発用のユニットテストヘルパー
    • パッケージのテストでLaravelのコアクラスを利用できる

作業場所

$ cd docker
$ docker-compose exec app ash
$ cd /packages/laravel-hello-world

作成するファイル・ディレクトリ

$ touch .gitignore
$ touch phpunit.xml
$ mkdir tests
$ touch tests/TestCase.php
$ touch tests/ExampleTest.php

空のファイル・ディレクトリを作成しておきます。

.gitignore を編集

/vendor
/composer.lock
/.phpunit.result.cache

テストライブラリの導入

$ composer require phpunit/phpunit --dev
$ composer require orchestra/testbench --dev

phpunit のバージョン確認

$ ./vendor/bin/phpunit --version
PHPUnit 8.3.4 by Sebastian Bergmann and contributors.

composer.json を編集

    "autoload-dev": {
        "psr-4": {
            "UcanLab\\LaravelHelloWorld\\Test\\": "tests/"
        }
    }

※カンマ(,)に注意

オートローダ生成

$ composer dump-autoload

phpunit.xml を編集

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
         backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         verbose="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="MyPackage Test Suite">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist>
            <directory suffix=".php">src/</directory>
        </whitelist>
    </filter>
</phpunit>

テストの作成

tests/TestCase.php

<?php

namespace UcanLab\LaravelHelloWorld\Test;

use Orchestra\Testbench\TestCase as OrchestraTestCase;

abstract class TestCase extends OrchestraTestCase
{
}

tests/ExampleTest.php

<?php

namespace UcanLab\LaravelHelloWorld\Test;

class ExampleTest extends TestCase
{
    /**
     * @return void
     */
    public function testResolve()
    {
        $this->assertTrue(true);
    }
}

テストの実行

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

Runtime:       PHP 7.3.8 with Xdebug 2.7.2
Configuration: /packages/laravel-hello-world/phpunit.xml

.                                                                   1 / 1 (100%)

Time: 1.18 seconds, Memory: 12.00 MB

OK (1 test, 1 assertion)

参考

41
29
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
41
29