I work in a 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 doesn't work.

I tried to include in the test class the index.php, wp-load.php and when are included, phpunit doesn't work and exit throught "exit code 0" without do nothing -the error is shown in the PhpStorm Terminal, if i execute the command in the cmd, the cmd doesn't thrown any information, just a blank line.

Php Version: 7.3.3 PhpUnit Version: 7.5.9 Wordpress Version: 4.9.1

An example for a error is 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 had to include for doing work this test or what is the method to test the class correctly.


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 (through wp_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!

  • Thanks for the answer, I just install the wordpress core setup with phpunit following the documentation and now the problem is that phpunit doesn't recognize wordpress function i don't understand it. The last test say "Call to undefined functions get_network()" in "wp-includes/functions.php". I need to include some wordpress file or something? Thanks again! – Ocriver May 8 at 13:14
  • That's a multisite function. You need to configure PHPUnit to work with multisite. Here's a good intro: codetab.org/tutorial/wordpress-plugin-development/unit-test/… – MikeNGarrett May 8 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.