4
7

More than 3 years have passed since last update.

PHPUnitでプライベートメソッドのテストを行う方法

Last updated at Posted at 2021-05-19

はじめに

通常の方法ではpublicメソッドしかテスト対象とすることができませんが、少しコードに手を加えることでprivateやprotectedのメソッドもテストができるようになります。
このページでは、private(protected)メソッドのテストを簡単に行うためのメソッドの紹介をします。

対象

  • Laravel
  • PHPUnit

ソースコード

/**
 * Execute private function test.
 *
 * @param $class 対象とするクラス
 * @param  string  $methodName メソッド名
 * @param  array  $arguments 引数(配列指定)
 * @return mixed
 */
protected function executePrivateFunction($class, string $methodName, array $arguments)
{
    $reflection = new ReflectionClass($class);
    $method = $reflection->getMethod($methodName);
    $method->setAccessible(true);

    return $method->invokeArgs($class, $arguments);
}

使い方

上記コードをテストコードのベースクラスに貼り付けます。
あとは、テストしたいコード上で該当メソッドを呼び出すことでprivateメソッドのテストが可能です。

サンプル

/**
 * @test
 */
public function isReadSkip(): void
{
    $parentAttribute = new ParentAttribute('spreadsheetCategoryName', 'sheetName');
    $parentAttribute->setParentAttributeDetails('Users', 'tableName');
    $parentAttribute->setParentAttributeDetails('user_db', 'connection');
    $argument = [
        'category_name'               => 'MasterData',
        'use_blade'                   => 'master_data',
        'sheet_id'                    => 'sheet_id',
        'output_directory_path'       => base_path('definition_document/database/master_data'),
        'separation_key'              => 'ColumnName',
        'attribute_group_column_name' => null,
    ];
    $fileOperation = $this->app->make(FileOperation::class);
    $spreadSheetReader = $this->app->make(SpreadSheetReader::class);

    /* @see SingleGroup::isReadSkip() */
    $singleGroup = new SingleGroup($fileOperation, $spreadSheetReader, $argument);
    $response = $this->executePrivateFunction($singleGroup, 'isReadSkip', [$parentAttribute, 'users']);
    self::assertFalse($response);
}

補足

プライベートメソッドのテストは通常書く必要は無いはずです。
どうしてもプライベートメソッドをテストしたい場合にだけ利用するくらいがちょうど良いと思います。

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