Manual:Writing testable PHP code/zh

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

Don't assume global context
Accessing global variables (e.g. ) without declaring them first with the   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
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
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.

不要使用
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:

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

外部链接

 * Testable Code webinar by Tobias Schlitt
 * How to Write Clean, Testable Code techtalk by Miško Hevery