I’m going to make a quick seminar for my team on how to improve the testability of our (15 years old) PHP code-base. Do you have any specific tips and tricks we can follow? Currently we’re using the Yii 1.1 framework, with PHPUnit and Facebook WebDriver with Serentiy for functional tests.
Some things I thought about:
- Include dependency injection where possible – e.g. inject the
$request
object instead of hacking$_POST
and$_GET
everywhere (but where is it possible in an old code-base?) - Functions should not hack global state if they don’t need to (related to point above)
- Functions with no side-effects are the easiest functions to test, so side-effects should happen as far up in the stacktrace as possible (hard to implement, examples needed)
- Functions should be short
- Functions should only do one thing
- Functions should have a clear relation between input and output (“contract” in some sense; also related to side-effects)
- First line of a function’s docblock should explain the relation between input and output – this line is what needs to be tested
- Controllers should be as small as possible, and basically just bake the input and feed it to models and helpers
- (Also include example of code that’s hard to test, and how to improve its testability) Thoughts? Which rules or habits do you use in your workplace?
Edit:
Some open questions:
- Are objects more easy to test than arrays? Should associative arrays (always) be replaced by objects?
- What’s best from a testability perspective: using exceptions or result objects/result array to propagate errors?
submitted by /u/usernameqwerty002
[link] [comments]