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 … Read more

unit testing admin password

I’m writing up unit tests for my plugin and I need a logged in user to test, but I can’t find the admin password anywhere. Does anybody know what the default admin password is? I’m extending the WP_UnitTestCase and taking the tests from https://unit-tests.svn.wordpress.org/trunk. My code at the moment: <?php require_once(‘myPlugin.php’); class MyPluginTest extends WP_UnitTestCase{ … Read more

how to set context in WordPress for unit testing

I have created a wordpress plugin which converts shortcodes to content based on the entry saved on the dataase: global $wpdb; $post_id = get_the_ID(); $post_content = get_the_content(); $pattern = ‘/\[zam_tweets page=([0-9])\]/’; preg_match($pattern, $post_content, $matches); if(!empty($matches)){ $tweets_table = $wpdb->prefix . ‘zam_tweets’; $result = $wpdb->get_var(“SELECT tweet FROM $tweets_table WHERE post_id = ‘$post_id'”); $content = $result; } return … Read more

DataBase connection problem with PHPUnit and WordPress

I’m trying to run PHPUnit to unittest a WordPress plugin, but the error below keeps showing up. Warning: mysqli_real_connect(): (HY000/2002): No such file or directory in /private/tmp/wordpress/wp-includes/wp-db.php on line 1452 I used WP-CLI to setup the unittests, but also WP-CLI throws a similar error when I try to run it. I use MAMP to run … Read more

Why is WP_Mock not used instead of WP_UnitTestCase for writing unit tests by most plugins?

For writing unit-tests, why do most plugins use WP_UnitTestCase instead of popular libraries like WP_Mock? The reason I am asking this is because WP_UnitTestCase doesn’t seem to be a unit test case but integration test as it requires WordPress-test environment & make actual DB-calls to WordPress-test-db? While WP_Mock mocks all WP functions and you can … Read more

How do I mock get_adjacent_post for testing

I’m trying to mock get_adjacent_post for unit testing but I’m not sure how to mock global function in PHPUnit $badCode = $this->getMockBuilder(‘get_adjacent_post’) ->setMethods(array(‘somthing’)) ->getMock(); Here’s what I got so far which obviously doesn’t work. And here’s how I use it in production code. $prev_post = get_adjacent_post( true, ”, true, ‘topic’ ); 2 Answers 2 I … Read more