質問

fwiw私はSimpleTest 1.1alphaを使用しています。

私はシングルトンのクラスを持っています。クラスをインスタンス化しようとすることでクラスがシングルトンであることを保証するユニットテストを書きたいと思います(プライベートコンストラクターがあります)。

これは明らかに致命的なエラーを引き起こします:

致命的なエラー:プライベートフロントコントローラーへの呼び出し:: __ construct()

その致命的なエラーを「キャッチ」し、合格したテストを報告する方法はありますか?

役に立ちましたか?

解決

いいえ。致命的なエラーは、スクリプトの実行を停止します。

そして、そのようにシングルトンをテストすることは本当に必要ありません。コンストラクターがプライベートであるかどうかを確認することを主張する場合は、使用できます ReflectionClass:getConstructor()

public function testCannotInstantiateExternally()
{
    $reflection = new \ReflectionClass('\My\Namespace\MyClassName');
    $constructor = $reflection->getConstructor();
    $this->assertFalse($constructor->isPublic());
}

考慮すべきもう1つのことは、シングルトンのクラス/オブジェクトは、ock笑するのが難しいため、TTDの障害であるということです。

他のヒント

これがMCHLの答えの完全なコードスニペットです。これがドキュメントを通過する必要がないように...

public function testCannotInstantiateExternally()
{
    $reflection = new \ReflectionClass('\My\Namespace\MyClassName');
    $constructor = $reflection->getConstructor();
    $this->assertFalse($constructor->isPublic());
}

Phpunitのプロセス分離などのコンセプトを使用できます。

これは、テストコードがPHPのサブプロセスで実行されることを意味します。この例は、これがどのように機能するかを示しています。

<?php

// get the test code as string
$testcode = '<?php new '; // will cause a syntax error

// put it in a temporary file
$testfile = tmpfile();
file_put_contents($testfile, $testcode);

exec("php $tempfile", $output, $return_value);

// now you can process the scripts return value and output
// in case of an syntax error the return value is 255
switch($return_value) {
    case 0 :
        echo 'PASSED';
        break;
    default :
        echo 'FAILED ' . $output;

}

// clean up
unlink($testfile);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top