Jump to content

Manual:Writing testable PHP code/ja

From mediawiki.org
This page is a translated version of the page Manual:Writing testable PHP code and the translation is 28% complete.

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

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

Accessing global variables (e.g. $wgRequest) without declaring them first with the global keyword will cause failures and E_NOTICE messages to be generated if they are accessed in a non-global context.

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

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!" );

This will allow PHPUnit and MediaWiki to exit properly and provide informative information such as stack traces to developers.

外部リソース