LoginSignup
0
2

More than 5 years have passed since last update.

PHPUnit でパースエラーを捕捉

Posted at

PHP の Extention を開発中です。引数のチェックは厳重にやりたいので、いろんなエラーケースを書いていたところ、参照渡しでハマりました。

vagrant@php-reform:~/php/ext/aha$ phpunit

Fatal error: Only variables can be passed by reference in /usr/local/src/php-7.1.4/ext/aha/tests/FE2Test.php on line 14

この FE2Test.php のソース自体がパースエラーになるので、phpunit 全体が失敗してしまうようです。

<?php
use PHPUnit\Framework\TestCase;

class FE2Test extends TestCase
{
  /**
   * 第二引数の型がリファレンスでないと Fatal Error
   * @expectedException ParseError
   */
  public function testArg2IsReference()
  {
    $handle = aha_MbSend([], "test");
    $content = "";
    $this->assertFalse(aha_MbReceive($handle, [], $content));
  }
}
vagrant@php-reform:~/php/ext/aha/tests$ php -l FE2Test.php

Fatal error: Only variables can be passed by reference in FE2Test.php on line 14

aha_*() は自分で書いた Extention の中の関数です。aha_MbReceive() の第二引数はリファレンスとして定義してあるため、パースでコケて実行まで行かないようです。

ぐぐってみると、Testing PHP parse errors with phpunitで解決策を見つけました。結果的に、以下のように書くだけでテストが通るようになりました。

(中略)
  /**
   * 第二引数の型がリファレンスでない
   * @expectedException ParseError
   */
  public function testMbReceiveArg2IsReference()
  {
    eval('<?php
$content = "";
aha_MbReceive(self::$handle, [], $content);
');
  }

コツとしては、とにかく「php -l ソースファイル」でコケたら負けということのようです。

参照

PHP7調査(23)致命的エラーが例外としてキャッチできるようになった

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