Unit Test in Wordpress
-
15-04-2021 - |
Pregunta
I work in wordpress with a lot of classes that use wordpress functions and I'd like make unit tests for them. The problem I found is that phpunit doesn't recognize wordpress functions and the tests don't work.
I tried to include in the test class the index.php, wp-load.php and when they are included, phpunit doesn't work and exits through "exit code 0" without do anything -the error is shown in the PhpStorm Terminal. If I execute the command in the cmd, the cmd doesn't throw any information, just a blank line.
Php Version: 7.3.3 PhpUnit Version: 7.5.9 Wordpress Version: 4.9.1
An example of an error is to test for a class with "add_action" in their constructor and the error is: "Call to undefined function add_action()". I don't know what file I have to include for doing work this test or what is the method to test the class correctly.
Solución
Take a look at the WordPress core setup with PHPUnit: https://make.wordpress.org/core/handbook/testing/automated-testing/phpunit/
Using this process rather than rolling your own allows you to leverage the boostrapping (and other customization) specific for WordPress.
From the Codex:
When
phpunit
is invoked, the test suite runs a script that sets up a default installation of WordPress, with a configuration similar to what you get with the GUI install. Before any tests are run, the following steps take place:
- WordPress is bootstrapped (by including
wp-settings.php
). This means that all tests run after the entire WP bootstrap (throughwp_loaded
).- All default content is deleted. This includes sample posts and pages, but does not include the default user or the ‘Uncategorized’ category.
Hope that helps!
Otros consejos
I can highly recommend wp-browser for that task.
https://github.com/lucatume/wp-browser
I've already written tests for entire websites, for .org plugins and premium plugins using wp-browser. It has unit, integration (same as Core's PHPUnit setup), acceptance (like with a Selenium server) and functional servers out of the box, all designed and architected to work with WordPress.