Wordpress Unit Testing - Cannot Create Tables

I'm using PHPUnit to Unit Test my WP plugin on top of the WP testing suite. Everything works fine except that when I try to create a table via the setUp method, the table doesn't get created. Here's my code: class Test_Db extends PAO_UnitTestCase { function setUp() { parent::setUp(); global $wpdb; $sql = "CREATE TABLE {$wpdb->prefix}mytest ( id bigint(20) NOT NULL AUTO_INCREMENT, column_1 varchar(255) NOT NULL, PRIMARY KEY (id) ) ENGINE=MyISAM"; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $this->el(dbDelta($sql)); } function tearDown() { …
Category: Web

no_rest_route in Unit Testing for REST endpoint for CPT registered via show_in_rest

I've created a REST route for custom post type 'book' by passing 'show_in_rest' => true, as args in register_post_type('books', $args); So, when I enter in URL https://localhost/wordpress/wp-json/wp/v2/books I can get the CPT. All good at this point. But, when using it in the tests, I'm facing an issue: Test Class: private $server; public function setUp() { parent::setUp(); global $wp_rest_server; $wp_rest_server = new WP_REST_Server; $this->server = $wp_rest_server; do_action('rest_api_init'); } the actual test: public function testBookEndpoint() { $request = new WP_REST_Request('GET', '/wp/v2/books'); …
Category: Web

How do I unit test a plugin with forms?

I've written my first serious WordPress plugin. Before I continue development on the plugin any further, I want to start writing tests for it. I've successfully installed phpunit and have got a test environment for the plugin up and running with WP_UnitTestCase. The plugin generates a 5 step form meaning the user starts with Step 1, hits submit, goes to Step 2, hits submit (or goes back to step 1), etc. until the form is filled out and spits out …
Category: Web

PHPUnit Plugin Integration Tests: Getting wordpress-tests-lib PHP into IDE (VS Code)

So I've managed to follow the instructions to get the "Plugin Integration Tests" set up using wp-cli and the install-wp-tests.sh script as described in the handbook article: https://make.wordpress.org/cli/handbook/misc/plugin-unit-tests/ After much hassle and debugging of a million things, I even have an example test running, yay! It's possible! Don't give up! My issue: The custom PHPUnit extensions for WP aren't picked up by my IDE. The /wordpress-tests-lib/ directory is deep in the bowels of my Mac, where install-wp-tests.sh installed it along …
Category: Web

Testing custom API endpoint with class dependency

Sorry I feel like really stuck here. I have a plugin introducing a new Rest API controller (WP_REST_Controller) with basically a single endpoint which uses a separate class as a client to fetch some data. Let's say: #my_plugin.php function register_items_routes() { if ( ! class_exists( 'WP_REST_My_Controller' ) ) { require_once __DIR__ . '/class-wp-my-controller.php'; } if ( ! class_exists( 'My_Class' ) ) { require_once __DIR__ . '/class-wp-my-class.php'; } $controller = new WP_REST_My_Controller(new My_Class); $controller->register_routes(); } add_action( 'rest_api_init', 'register_items_routes' ); _ #class-wp-my-controller.php …
Category: Web

Mocking WP_CLI static methods in unit tests

I'm writing unit tests (not integration) for a lib I'm working on. There, we created some WP-CLI commands that I'd like to test. Most of them are just renaming things, copying and pasting things over from the lib to the project. And when something is successful or not a WP_CLI::success() or similar methods are used to output the message to the user (log, warning or error). So what I'd like to do is just to output the contents of those …
Category: Web

How can I enable IDE integration (autocomplete) for WordPress test suite

When testing a theme or plugin, you can use WP-CLI to scaffold the test suite setup, wp scaffold plugin-test plugin. So is there a good way to integrate an editor/IDE (VS Code in my case) so that autocompletion (method signatures, etc) works within the tests? Since the test library is installed in /tmp/ the editor is not indexing those files and thus thinks classes and functions are missing.
Category: Web

Unit Test in Wordpress

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 …
Category: Web

Unable to find PHPUnit code coverage stats

Where should I check for the code coverage stats when using PHPUnit for WordPress? My WordPress setup: I have setup WordPress using VVV and my testing suite includes PHPUnit and WP-CLI. How I executed test cases to find code coverage? When I execute phpunit command to test a WordPress plugin, I'm able to see, if the test cases passed or failed. In my case there were no failures. To find the code coverage, I executed phpunit --coverage-text=./coverage.txt, the test cases …
Category: Web

How do I phpunit test a post output process?

I like to know how to test the html output of a post. Like WP would output it on the frontend in reality. My specific case at this point is to test oembed caching as I want to test re-caching. AFAIK WP does only cache oembed results if they are associated with a post. So I can not just run some text though the_content filter. I like to test the real post processioning for this and in general for other …
Category: Web

How to verify meta box is registered in Unit Testing?

I am currently doing TDD with WordPress, in the PHPUnit I need to test if the meta box is actually registered on a method call, I could not find any function in WordPress to do that, so I was trying to verify it by calling global $wp_meta_boxes, but it returns null when invoked inside a PHPUnit test. Is this variable is assigned on a hook? Could any one provide the action/filter name?
Category: Web

Why is one phpunit test throwing an error on one class when all other classes are similar without error?

I'm working on the Liquid Messages plugin. There are some basic PHPUnit tests existing for it and when I run phpunit all pass except for one. It errors out: There was 1 error: 1) GCS_Async_Test::test_class_access Exception: Invalid GC_Sermons_Plugin property: async /long/path/wp-content/plugins/lqd-messages/gc-sermons.php:330 /long/path/wp-content/plugins/lqd-messages/tests/test-async.php:10 The weird thing is that gc-sermons.php contains a number of properties similar to this one. They are initialized like so: protected $sermons protected $taxonomies protected $async Instances of the classes are attached to the properties: public function plugin_classes() …
Category: Web

PHPUnit Testing and woocommerce Constant

I tried to perform a test on the WC_VERSION constant. The main class : class WC_Custom_Variable_Products_Dependencies { /** minimum WooCommerce version required by this plugin */ const MINIMUM_WC_VERSION = '3.7.9'; public function __construct() { add_action( 'admin_init', [$this, 'check_wc_version']); } protected function check_wc_version() { return version_compare(WC_VERSION, self::MINIMUM_WC_VERSION , '>='); } } The test class : require_once 'includes/class-wc-custom-variable-products-dependencies.php'; class WC_Custom_Variable_Products_DependenciesTest extends WP_UnitTestCase { public function setUp() { parent::setUp(); $this->class_instance = new WC_Custom_Variable_Products_Dependencies(); } /** * Tests the protected functions * * @param …
Category: Web

Unit Testing action hook

I want to perform unit tests on a Class, my goal is: I want to check if the plugin is activated or not by using the function: is_plugin_active class WC_Custom_Variable_Products_Dependencies { public function __construct() { add_action( 'admin_init', [$this, 'check_environment']); } public function check_environment(){ return is_plugin_active( 'woocommerce-custom-variable-products/woocommerce-custom-variable-products.php' ); } } CLass de test : require_once 'class-wc-custom-variable-products-dependencies.php'; class WC_Custom_Variable_Products_DependenciesTest extends WP_UnitTestCase { public function setUp() { parent::setUp(); $this->class_instance = new WC_Custom_Variable_Products_Dependencies(); } public function test_check_environment(){ $result = $this->class_instance->check_environment(); $this->assertTrue($result); } The assertion …
Category: Web

Access post from post id in URL

I'm doing unit tests for my plugin, and in my unit test, I check some basic things such as posting a custom post type. My script can create new post, and I can retrieve the ID of the posted item (I'm redirected to an URL like http://wordpress.loc/wp-admin/post.php?post=16&action=edit&message=6, so I can deduce that the new post has the ID 16). From this ID, I'd like to check if the post is as it should be by accessing it via URL, with …
Category: Web

Coverage in integration tests

EDIT: I've created the mwe as a small test plugin: https://github.com/dingo-d/test-plugin Original question: I'm writing tests for my plugin and one thing makes no sense to me and I'm not sure if I'm doing something wrong, or is it just PHPUnit behaving in a certain way. In a class I have a register()method where I add my hooks. When I write a test, I usually instantiate my class (even though I shouldn't because I'm running integration test so when I …
Category: Web

Integration tests test script enqueue/register fails

This question is related to this SO post I'm testing a plugin, and in it I have public function enqueue_scripts() { $main_style = 'public/scripts/application.js'; wp_register_script( 'plugin-scripts', plugin_dir_url( __DIR__ ) . $main_script, array() ); wp_enqueue_script( 'plugin-scripts' ); } The plugin is using composer and npm, so it needs to be built to work. And it is built (locally where I'm testing it, it works in a local instance I have on VVV). The test I wrote looks like this public function …
Category: Web

Error when setting up phpunit tests with wp-cli scaffold

I am trying to figure out the setup for unit tests for wordpress plugins. I am using Ubuntu. So far I have: Local WordPress Installation WP-CLI up and running Installed phpunit used wp scaffold command to generate unit test files When I now try and run the phpunit command I get the following error: PHP Warning: require_once(/tmp/wordpress//wp-includes/class- phpmailer.php): failed to open stream: No such file or directory in /tmp/wordpress-tests-lib/includes/mock-mailer.php on line 2 PHP Fatal error: require_once(): Failed opening required '/tmp/wordpress//wp-includes/class-phpmailer.php' …
Category: Web

Wordpress and Wordpress-test-lib not getting added to tmp folder

I’ve installed the wpcli and php unit testing to my imac and the wordpress and wordpress-test-lib files were added to my tmp folder as they should have. I used this to install the setup. bash bin/install-wp-tests.sh wordpress_test root <mypassword> localhost latest I wanted to reinstall everything to make sure I had the process down so I could show others. However, after deleting the files from the tmp folder and reinstalling using the terminal command bash bin/install-wp-tests.sh wordpress_test root <mypassword> localhost …
Category: Web

Using wp_mail during an integration test

I'm working on some tests for WordPress, and I discovered that WordPress' PHPUnit automatically captures and doesn't send emails (using MockPHPMailer) when I try to use wp_mail. I've looked, but I can't seem to find any information on MockPHPMailer. I'd love to know either how to use it or disable it (since before this discovery I'd planned to use Mailtrap). Does anyone know where I might find some information about MockPHPMailer?
Category: Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.