0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

LaravelとPHPUnitでDB操作クラスの単体テストを行う

Last updated at Posted at 2021-11-17

LaravelとPHPUnitでDB操作クラスの単体テストを実装しました

テストの準備

テスト対象のドメインクラス

<?php

namespace App\Domains\AdminCompany;

class AdminCompany
{
    private $adminCompanyName;

    public function __construct(
        AdminCompanyName $adminCompanyName,
    ) {
        $this->adminCompanyName = $adminCompanyName;
    }


    public function getName(): ?AdminCompanyName
    {
        return $this->adminCompanyName;
    }
}

テストコード

Note: テストクラスに独自のsetUpメソッドを定義する場合は、親のクラスのparent::setUp()/parent::tearDown()を確実に呼び出してください。

<?php
namespace Tests\Unit\Domains\AdminCompany;

use App\Domains\AdminCompany\AdminCompany;
use ArgumentCountError;
use PHPUnit\Framework\TestCase;

class AdminCompanyTest extends TestCase
{

    private $adminCompanyName;

    protected function setUp(): void
    {
        // 必須
        parent::setUp();

        $this->adminCompany = new AdminCompany(
            $this->adminCompanyName = new AdminCompanyName('example'),
        );
    }

    public function test_コンストラクタに何も渡さない場合はエラーになる()
    {
        $this->expectException(ArgumentCountError::class);
        new AdminCompany();
    }

    public function test_getName_コンストラクタに正しインスタンスを渡すと渡された値を返す()
    {
        $this->assertEquals($this->adminCompanyName, $this->adminCompany->getName());
    }
}

テストを実行する

./vendor/bin/phpunit

==== Redirecting to composer installed version in vendor/phpunit ====

PHPUnit 7.5.9 by Sebastian Bergmann and contributors.

..........                                                        2 / 2 (100%)

Time: 8.11 seconds, Memory: 24.00 MB
OK (2 tests, 2 assertions)

CI/CDするのは品質を維持できるのでぜひ導入してみてください!

最後に

読んでいただきありがとうございます。
今回の記事はいかがでしたか?
・こういう記事が読みたい
・こういうところが良かった
・こうした方が良いのではないか
などなど、率直なご意見を募集しております。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?