Manual:Writing testable PHP code/ja

Some notes on writing testable, code, to be expanded on at some point.

グローバル コンテキストを想定しない

グローバル変数 (例: $wgRequest) を、最初に global キーワードで宣言せずにアクセスすると、失敗が発生し、非グローバル コンテキストでアクセスされた場合には E_NOTICE メッセージが生成されます。

グローバル変数を新規作成しない

While putting information in global variables seems easy, it makes the code less predictable. By relying on global variables, you are making it difficult to isolate functionality. A singleton class is better for testing (but, still, less than ideal).

直接入力のみを信頼する

While this is not always achievable, it is best to write code that depends only on direct inputs. That is, a class only uses the information it is passed and does not rely on singletons or globals to get “out-of-band” information.

<span id="Do_not_use_exit()">

exit() を使用しない

Exiting from a script abruptly should almost never be done. Doing so will make your code untestable by PHPUnit. If your code encounters an unexpected error, the proper thing to do is throw an exception like:

throw new MWException( "Oh noes!" );

これにより、PHPUnit と MediaWiki は正常に終了し、開発者にスタック トレースなどの有益な情報を提供できるようになります。

外部リソース

Category:Testing/ja#Writing%20testable%20PHP%20code/ja
Category:Testing/ja