Unit Testing Hack Day Recap

Yesterday, even though it was a beautiful Saturday afternoon, 15 of us gathered to level up our Unit Testing skills at the first PDXWP Hack Day.

After a couple of hours getting learned, we managed to ship:

To kick the day off, special guest Max Cutler introduced us to the many variants of unit testing. Check out his Speakerdeck for the full presentation.

Max emphasized writing unit tests to:

  • Verify your functionality. Does the code do what you want it to do?
  • Validate technical design. Code that’s easier to test is generally better code. Plus, tests document what you’re intending to do.
  • Protect against bugs. If you find a bug, both fix the bug and write tests to protect against the bug in the future.
  • Refactor with confidence. Core takes backwards compat seriously, so having unit tests to describe coverage makes it easier to change code.

Unit testing specifically tests individual methods and functions to confirm input equals expected output. Integration testing looks at the code from the users’ perspective — everything works as expected. In core’s test suite, most tests are integration tests.

Max walked us through how WordPress core uses PHPUnit for testing, with lots of concrete examples. Thanks to good work by Jeremy and Zack, most of us had the test suite up and running via Vagrant. Here’s one great reason to help increase core’s test coverage:

Mike Bijon then talked through including tests with your plugin. It can be difficult to know where to get started when you’re looking at a blank slate. 100% coverage is much more easily attainable when you’ve been writing tests from the beginning, or practicing test-driven development.

It can be much easier incorporating tests into your plugin by breaking it down:

  • WordPress doesn’t WOSD.
  • Your code loads.
  • Each method has a test.
  • Code coverage reports.

Fortunately, there’s a couple of easy ways to get started. wp-cli takes care of the busy work with a wp scaffold plugin-tests <plugin-name> command. This will add all of the necessary code to your plugin to start writing PHPUnit tests. It also includes a travis.yml file — all you need for basic Travis CI.

Thanks again to our speakers, and everyone who took time out of their Saturday afternoon to raise the knowledge.