Guide: Implementing a PhpUnit Development Environment in PhpStorm

Preperation

For this example, I will be starting with the following:

  • PhpTraits repository https://github.com/Waryway/PhpTraits
  • PhpStorm Project
    • Make certain you have a php interpreter referenced in your storm project
    • Also make certain you have Composer referenced by PHPStorm
    • A desire to test.allTheThings()
Adding the PHP interpreter reference.

Installing Libraries

First, use composer do some work. We need a copy of phpunit. Get it with this:

"require-dev":{
    "phpunit/phpunit":"6.4.3"
}

As this is a ‘library’ style app – use an exact version. The lock file gets ignored in favor of precise dependencies in the composer.json.

Now run composer update to pull in the requested phpunit package.

Setup phpunit in the general settings, under phpunit

Adding a new test

Or rather, a test skeleton

  1. Open the file to test in the Project View
  2. Place you cursor on a method to test within the file
  3. Go To Navigate -> Test
  4. Create New test
  5. I tend to set mine up with a test prefix to keep tests more obviously separate from code.
  6. Click Ok then Open up the new file
  7. Add a line to pull in the composer autoloader
  8. Clean up the Namespace reference to the TestCase if you are using PSR-4
  9. Disclaimer: Strongly avoid namespacing unit tests. They should not be built out like a code base. They are testing units.
  10. Add an empty testHydrate method.
  11. Add a super obvious assertion.
  12. Add a phpunit.xml fileI put it in the test directory.
  13. Run the test (At this point, I needed to restart phpstorm to detect that I actually had a ‘test’ to run.
  14. Build the tests out further.

Conclusion

Ending of the beginning

I’ve gone ahead and built out the ‘hydrate’ test against a trait. Note the use of the trait object that phpunit provides. Pretty slick, right?  I’ll continue to build out this repository – core libraries need the most directed test coverage.

Even adding the ‘test’ cases around the hydrate method – I have found use cases I didn’t consider while writing the code – and have adjusted the code to reflect the behavior I expect.