I need to apply unit testing for one of my plugins. I recently re designed it into classes, so unit testing should be easier to apply now.
What are some effective strategies to unit test my plugin? I need a way to use WordPress’ functions used in the plugin, but I shouldn’t need a running WordPress site (just test data on the DB AFAIK), right?
I have a hard time figuring out how to just unit test the plugin and not the plugin in the site’s context. I could use Selenium for this, but right now I just want to focus on unit testing the plugin classes functionality, so that I don’t break them with each update.
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
As an ex-software engineer building large business types who landed in an interactive agency let me give you a few thoughts on testing when developing for WordPress:
Your Unit Testing should test the smallest amount of behavior that a class can perform. Each class should be able to be tested independently of WordPress. If you have a WordPress dependency consider creating mock objects and/or methods in your test to work around this. Ultimately, this will change how you write your code a bit — but it will be far more testable. As usual no free lunch.
When you get up to the level of functional testing this is where you can test you code with WordPress dependencies. This is where you would actually test that your plugin actually performs a service it is supposed to.
Depending on what your plugin does — consider using Selenium-based tests which test for the presence of data in the DOM by using IDs. Its reasonably robust and it is a lot less likely to break version to version. Again, the trick here is to think of testing as part of your software development lifecycle. Large changes in the code will cascade down to large changes in your tests. All part of the cost of doing business.
If you need any assistance with any of the tools to accomplish this — I would be happy to answer if you open up a new question. I make use of both PHPUnit and its selenium extension in the work I do.
I’ve not actually done it myself, but there is a testing environment for WordPress unit testing. It’s meant for core testing, but it could be adapted to test plugins.
More info here:
I have recently created a tutorial that takes the info from my googling, to show how to:
- Use the wordpress core make unit tests
- Hide php deprecated/session sent warnings
- Show how to set your plugin options in the tests
- Use same wp core make unit tests to test multiple plugins
The tutorial is here, I hope it helps