0
0

【PHPフレームワークFlow】FlowのソースにPHPunitを試す

Last updated at Posted at 2024-06-01

初めに

Flowでソースを書いてきましたが、UnitTestはまだ書いたことがありませんでした。
今回は、PHPフレームワークFlowでUnitTestを書く方法をまとめます。

PHPunit

PHPUnitとは、PHPのUnitテストツールです。
豊富なAssertメソッドを有しているのが特徴です。

PHPUnit使ってみる

ということで、さっそく使ってみましょう。
今回UnitTestを作成するのはこちらのUsersクラスです。
getName()のUnitTestを作成したいと思います。

Users.php
<?php
namespace Neos\Welcome\Domain\Model;

use Neos\Flow\Annotations as Flow;
use Doctrine\ORM\Mapping as ORM;

/**
 * @Flow\Entity
 * @ORM\Table(name="users")
 */
class Users
{

    /**
     * @ORM\Column(length=80)
     * @var string
     */
    protected $name;

    public function __construct(string $name, string $email, string $password)
    {
        $this->name = $name;
    }

    /**
     * テスト対象
     */
    public function getName(): string
    {
        if (empty($this->name)) {
            return "unknown";
        }
        return $this->name;
    }

}

作成手順

ということで作成します。

1. インストールは不要

まずはインストール!と言いたいところですが、Flowのプロジェクトには最初からPHPUnitが入っているので、インストールは不要です。
プロジェクト直下のbinディレクトリを見ると、すでにphpunitの実行ファイルが入っていることが確認できると思います。

Project
  └ bin
      ├ phpunit
      └ phpunit.bat

Testファイル作成

続いてテストファイルを作成します。

UsersTest.php
<?php
namespace Neos\Welcome\Tests\Unit\Domain\Model;

use Neos\Welcome\Domain\Model\Users;

class UsersTest extends \PHPUnit\Framework\TestCase
{

    /**
     * @test
     */
    public function testGetName_unknown()
    {
        // Arrange
        $sut = new Users("", "test@example.com", "pass");

        // Act
        $result = $sut->getName();

        // Assert
        $this->assertSame("unknown", $result);
    }
    
    /**
     * @test
     */
    public function testGetName_known()
    {
        // Arrange
        $sut = new Users("a", "test@example.com", "pass");

        // Act
        $result = $sut->getName();

        // Assert
        $this->assertSame("a", $result);
    }
}

ポイントは以下です。

  • \PHPUnit\Framework\TestCaseクラスを継承
  • TestCaseクラスのassertメソッドを使って結果を確認
    • 今回はassertSameを使用
  • @testアノテーションがついているか、testから始まるメソッドがテスト対象になる

実行

ここまで出来たら実行しましょう。
先ほど確認したphpunitの実行ファイルを実行します。

$ .\bin\phpunit .\Packages\Application\Neos.Welcome\Tests\Unit\Domain\Model\UsersTest.php
PHPUnit 9.6.19 by Sebastian Bergmann and contributors.

..                                                                  2 / 2 (100%)

Time: 00:00.008, Memory: 4.00 MB

OK (2 tests, 2 assertions)

無事に実行できました!

終わりに

Flowでは、\PHPUnit\Framework\TestCaseクラスを継承したUnitTestCaseというクラスが用意されており、それを利用しても試験ができるようになっています。が、現状そのクラスを利用したUnitTestの実行でハマっています。解決したらまた記事にしようと思います。

ご覧いただきありがとうございました!

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