Manual:Writing testable PHP code

From MediaWiki.org
Jump to: navigation, search
MediaWiki Flower
« Unit testing
PHPUnit testing

Contents


Tools

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

Don't assume global context[edit | edit source]

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.

Don't create new global variables[edit | edit source]

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).

Rely only on direct inputs[edit | edit source]

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.

Do not use exit()[edit | edit source]

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.

External resources[edit | edit source]