LoginSignup
2
1

More than 5 years have passed since last update.

PHPUnitで別プロセステストをしたい場合、Elementなど別ファイルの呼び出しがある場合は注意!

Last updated at Posted at 2016-09-23

PHPUnitで別プロセステストをしたい場合、Elementなど別ファイルの呼び出しがある場合は注意!

PHPUnitでは、別プロセスでテストということが行うことができます。

    /**
     * testHoge
     *
     * ↓これを書く
     * @runInSeparateProcess
     */
    public function testHoge()
    {
    }

テストを実行するにあたって、ある理由で別プロセスでテストを実行する必要があったのですが・・・

起こったこと

とりあえずこんなテストを書きました。

<?php
namespace App\Test;

use Cake\TestSuite\TestCase;
use Cake\View\View;

class HogeTest extends TestCase
{

    /**
     * testHoge
     */
    public function testHoge()
    {
        $View = new View();
        //hoge.ctpには<?= $fuga;?>の記載がある
        $a = $View->element('hoge', ['fuga' => 'fugaa']);
        $this->assertTrue(true);
    }

    /**
     * testHoge2
     *
     * @runInSeparateProcess
     */
    public function testHoge2()
    {
        $this->assertTrue(true);
    }
}

結果

PHPUnit 5.5.5 by Sebastian Bergmann and contributors.

.E                                                                  2 / 2 (100%)

Time: 120 ms, Memory: 8.50MB

There was 1 error:

1) App\Test\HogeTest::testHoge2
PHPUnit_Framework_Exception: Notice Error: Undefined variable: fuga in [/var/www/html/htdocs/caketest/test/src/Template/Element/hoge.ctp, line 1]

ERRORS!
Tests: 2, Assertions: 1, Errors: 1.

!!?

testHoge2では見ての通りhoge.ctpなんて読み込んでいません。

どうしてこんなことが起こっているのか

とりあえずこれを見てくれ。。。

class PHPUnit_Util_GlobalState

    public static function getIncludedFilesAsString()
    {
        return static::processIncludedFilesAsString(get_included_files());
    }

はい、get_included_files()。。。

因みに、別プロセスで実行をする場合のみこのメソッドが走ります。

そして、別プロセスで実行する際には、現在includeもしくはrequireされたファイルを全てrequire_onceで読み込んでからテストを実行している訳です。

そういうわけで、hoge.ctprequire_onceで読み込まれちゃうのですが、当然require_once実行時において$fugaなんてありませんのでエラーが発生するというわけです。

解決策

こんなことが起きたら対処として考えられるのは

  • すべて別プロセスでテストする
  • 通常のテストと別プロセスのテストを完全に別のテストとして実行する(classレベルでなく実行するテストレベルで別

くらいしか対処が思いつかないです。。。

そもそも別プロセスなんかでテストを実行しなくて良いようにするってのが一番正しい気がする

2
1
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
2
1