WordPress

Write a testing code of registration for the custom wp-cron event by using PHPUnit

We can register a single cron job by using the WordPress function named wp_schedule_single_event. But sometime […]

広告ここから
広告ここまで

We can register a single cron job by using the WordPress function named wp_schedule_single_event.

wp_schedule_single_event( int $timestamp,  string $hook,  array $args = array(),  bool $wp_error = false )

But sometimes, we want to check for is the cron job truly registered.

And we can write a test code by using PHPUnit.

Simply testing example

First, we can test just a wp_schedule_single_event function.

class Cron_Test extends \WP_UnitTestCase {

    function test_cron_registration() {
        $hook = __FUNCTION__;
        $timestamp = strtotime( '+1 hour' );

        $scheduled = wp_schedule_single_event( $timestamp, $hook_name );

        // Check is the job has been registered
        $this->assertTrue( $scheduled );

        // Check is the scheduled time is correct
        $this->assertSame( strtotime( '+1 hour' ), wp_next_scheduled( $hook ) );

        // It's a non-recurring event.
        $this->assertFalse( wp_get_schedule( $hook ) );
    }

Ref: https://github.com/WordPress/wordpress-develop/blob/master/tests/phpunit/tests/cron.php#L39-L50

Register the cron job conditionally

If you want to register the job conditionally like the super simple example,

function testing_target_function( $timestamp, $hook_name, $flag ) {
    if ( false === $flag ) {
        return false;
    }
    return wp_schedule_single_event( $timestamp, $hook_name );
}

we can test by the following code.

class Cron_Test extends \WP_UnitTestCase {

    /**
     * @dataProvider provide_test_cron_registration_test_case
     */
    function test_cron_registration( $flag, $should_scheduled ) {
        $hook = __FUNCTION__;
        $timestamp = strtotime( '+1 hour' );

        $scheduled = testing_target_function( $timestamp, $hook, $flag );
        $this->assertEquals( $should_scheduled, $scheduled );

        if ( $should_scheduled ) {
            $this->assertSame( $timestamp, wp_next_scheduled( $hook ) );
        }
        // It's a non-recurring event.
        $this->assertFalse( wp_get_schedule( $hook ) );
    }

    function provide_test_cron_registration_test_case() {
        return [
            [ false, false ],
            [ true, true ],
        ];
    }
}

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts