Here are some tips for making PHPUnit tests:
- Create tests before actually coding the method to ensure the method actually does what it is being tested to do.
- In PHPStorm from within the class press
ALT+INSERTto automatically create a UnitTest. - UnitTests should be able to run without a database.
- Setup multiple testSuites to break unit tests into smaller packages. This also allows for UnitTests that require a database access to be separated.
- Generate coverage reports to see the test is actually doing. Add more assertions until 100% of method is tested.
- Add PHPUnit tests to CI to get instant feedback on PR (TravisCI, etc.). Don't count on developers running PHPUnit tests locally only.
- Add coverage report generation to CI (TravisCI, Github Action, etc.)
- Add coverage badge/shield and CI PHPUnit test pass badge to repo README.md.
- SOLID methods are easier to code and maintain. A method should not feature the word "And" for example, e.g. "processAndCheck()".
- Generally, a method should throw and error rather return whether it was successful or not as a bool. Test for whether error is asserted.
- If a method has an else statement chances are it should be refactored. Use a return instead and consider the methods cyclomatic complexity.
- Code should be written to be testable. Chances are a code base without tests is not as testable as a code base with tests.
- ...