Automattic / WPCOM-Legacy-Redirector

WordPress plugin for handling large volumes of legacy redirects in a scalable manner.
20 stars 16 forks source link

Tests: Add unit test structure for WP-CLI class #97

Closed GaryJones closed 3 years ago

GaryJones commented 3 years ago

We need to manually load WP-CLI when we bootstrap PHPUnit so the relevant classes are loaded.

Strictly speaking when it comes to unit tests, we shouldn’t need to bootstrap any dependency like this, as we aren’t testing WP-CLI and so don’t care about it, but as our class extends from a WP-CLI class, there isn’t a way to swap that out for a mocked class without some over-engineered class SPL aliasing in our actual plugin.

See https://polevaultweb.com/2016/11/unit-testing-custom-wp-cli-commands/ - kudos to @polevaultweb for solving this problem 4 years ago and blogging about it 👍🏻

Includes a simple unit test to confirm that the custom WP-CLI class can be instantiated.

With this CLI test structure in place, we could write some tests for this class, which would allow refactoring existing commands (move some of the logic out of the command method / CLI class so it can be re-used regardless of where the input comes from) and adding new commands with more confidence. The command methods should collect the input, and pass to a different (mockable) class, which makes it perfect for pure unit tests.


We could also/instead write Behat tests for it, which seems to be what is favoured for WP-CLI. I tried to follow https://deliciousbrains.com/writing-functional-tests-wp-cli-packages/ but couldn't get it working with my local setup.