1

I've a simple PHP Unit written for WordPress and want the initialize code before the main 'init' action being called from the plugin I want to test, e.g.

class MyPlugin_Test_Example extends WP_UnitTestCase {

    public static function setUpBeforeClass()
    {

        error_log('setUpBeforeClass');

    }
...

For example, I have put a log statement in the setUpBeforeClass already, but it is still being called after the 'init' action of my plugin.

Suppose my plugin's init action need something to check, is it possible to let me test code fake that anyway?

2

What you have discovered is that WordPress is loaded—and all of the actions are called—before the tests run. It is possible to hook into an action when WordPress is loaded, but it has to be done from your PHPUnit bootstrap file instead of from the testcase class. I don't know what your bootstrap file looks like, so I'm going to assume that it is something similar to the one in this tutorial. The main thing that you need to do is load the file containing WordPress's PHPUnit helper functions (tests/phpunit/includes/functions.php). You'll need to be including that file because it contains the tests_add_filter() function. And that's the function you can use to hook into init, like this:

tests_add_filter( 'init', 'my_function_to_call' );

The function works the same as the add_filter() or add_action() functions. You can't use add_action() though, because WordPress hasn't been loaded yet, and therefore those functions aren't available. And as you've discovered, you can't wait until after WordPress is loaded to hook up your function, because then it will be too late. That's why the tests_add_filter() function exists: so you can hook into WordPress before it is loaded for the tests.

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.