Skip to content

Instantly share code, notes, and snippets.

@hxtree
Created June 22, 2021 13:48
Show Gist options
  • Select an option

  • Save hxtree/2337de60fcbe945334da9f47d6e43833 to your computer and use it in GitHub Desktop.

Select an option

Save hxtree/2337de60fcbe945334da9f47d6e43833 to your computer and use it in GitHub Desktop.
Tips for PHPUnit Tests

Tips for PHPUnit Tests

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 + INSERT to 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.
  • ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment