WordPress Unit Tests naturally play a big part in making sure that new features introduced into core work as expected and that previous features do not break. And pushing forward with more test coverage is a Good Thing™.

In the last couple of plugins, I’ve released into the WordPress Plugin Repository, I’ve included unit tests with the plugin. Of course, these aren’t for the users benefit (why would they be?).

The way I see it if we’re working with open source, why not include these tests for those who may download, run, fork, test, or explore the code base?

But there’s a thing about these unit tests: They inherit from WP_UnitTestCase. And the more I work with creating plugins for fun, for profit, and for others, the more I think that unit tests we ship with our plugins don’t necessarily need to inherit from that class.

WordPress Unit Tests: The Source Code on Trac

Instead, they should inherit from the standard set of classes provided by PHPUnit.

WordPress Unit Tests and Plugins

I don’t mean to make this an either/or issue:

It’s not like I’m saying that we should be including either vanilla PHPUnit-based tests or WordPress Unit Test Cases. But I do think we need to be strategic in how we write our tests because they are a direct reflection of how we organize our code.

For instance, if we couple the business logic of our plugin or, more simply, the logic responsible for doing the actual work of our plugin, to WordPress-specific APIs all in the same class, then our coupling is too high.

This means we’re going to have to write tests that use WP_UnitTestCase.

On the other hand, if we’re able to use standard PHP unit tests with the classes that are core to our plugin, then perhaps we’re on to a stronger object-oriented architecture. After all, we can run the WordPress core unit tests at any time.

But if our plugin requires the core testing framework, are we designing our plugin in the best way possible?

I do believe there are caveats (remember, this isn’t an either/or issue). For example, if you have a class that’s working with the WordPress database or something related to the underlying schema (or perhaps even a custom table), then using the WP_UnitTestCase makes sense.

But that’s more of an exception than a rule. It’s something we should be using sparingly.

Regardless, perhaps this is a form of a litmus test when it comes to writing object-oriented WordPress plugins:

  • If the class you’re testing must use the framework for WordPress Unit Tests but it’s not testing core, is your class too tightly coupled?

And my opinion on this may change over time (as it tends to do for anyone who’s read this blog long enough). But I know that, for now, there are a couple of plugins I’d like to refactor and unit tests I need to update.

Share:

Leave a Reply