0
votes

I'm trying to use PHP Unit to test an API class that I've written to work with an addon for the WordPress plugin Gravity Forms. The class is dependent on several functions from WordPress such as wp_remote_request().

In order to have access to these WordPress dependencies, I'm trying to require wp-load.php in my PHP Unit test class using:

define( 'WP_USE_THEMES', false );
require '../../../wp-load.php';

However, when I try this, I get the following output in my terminal upon running phpunit:


    Cannot modify header information - headers already sent by (output started at phar:///usr/local/Cellar/phpunit/6.4.2/libexec/phpunit-6.4.2.phar/phpunit/Util/Printer.php:112)

    ../wp-includes/functions.php:3760
    ../wp-includes/load.php:422
    ../wp-settings.php:110
    ../wp-config.php:228
    ../wp-load.php:37
    ../wp-content/plugins/gravity-dpo/tests/TestCaseAddon.php:37

Looking at the wp-includes/functions.php file, I can see the following class at line 3760 within the function dead_db(), which is what causes the error:

header( 'Content-Type: text/html; charset=utf-8' );

Surely it should be trivial to require wp-load.php so I can test a class with some WordPress dependencies using PHP Unit? I would appreciate any pointers as to what I'm doing wrong here. I'm trying to avoid having to create a fully fledged WordPress unit testing set up because I just want to test one or two functions from my API class.

1
I'm really not experienced with phpunit, but why wouldn't you just mock these functions? - janh
That's an option, but shouldn't it be simple for this to work the way I'm trying to do it? - Benjamin Brown
Also, I need to test based on the results of an actual GET request, so I'm not convinced it would be easier to mock these methods than to get the WordPress dependencies to work - Benjamin Brown

1 Answers

1
votes

On occasion you may want to test some functionality without actually creating a plugin/add on to do so. Create a test.php file with the following code snippet and place it in your WordPress root directory:

<?php
// Load the WordPress Environment
// define( 'WP_DEBUG', true ); /* uncomment for debug mode */
require(./wp-load.php);
// require_once (./wp-admin/admin.php); /* uncomment for is_admin() */
?>
<pre>
<?php
/* test stuff here */
var_dump( is_admin() );
?>
</pre>

This is a quick way to load all of the required WordPress functions to test plugin functionality without actually creating a plugin. As you can see wp-load.php is included at the beginning of the file. You can also include wp-admin/admin.php if you want to test admin side functionality.

Once you have included the required WordPress core files, you want test any code that would otherwise exist reside in your plugin. Don’t forget to remove your test.php file when you are done testing.