1

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.

1
2

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!

2
  • 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 '19 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 '19 at 13:22
0

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.

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.