[WP Plugin Dev] PHPUnit でプラグインのテスト駆動開発

memo.

WordPress プラグインのユニットテスト環境を作る」の続き。写経。

サイトの拡張性を飛躍的に高める WordPressプラグイン開発のバイブル
SBクリエイティブ (2014-08-07)
売り上げランキング: 67,805

テストを書く

wordpress/wp-content/plugins/sandbox-hatamoto/tests/test-twitter-shortcode.php
<?php
/**
 * Class TwitterShortcodeTest
 *
 * @package Sandbox_Hatamoto
 */
class TwitterShortcodeTest extends WP_UnitTestCase {
    function test_twitter_shortcode() {
        $html = do_shortcode( '[twitter]@driftwoodjp[/twitter]' );
        $this->assertEquals( '<a href="https://twitter.com/driftwoodjp">@driftwoodjp</a>', $html );
        // without @
        $html = do_shortcode( '[twitter]driftwoodjp[/twitter]' );
        $this->assertEquals( '<a href="https://twitter.com/driftwoodjp">@driftwoodjp</a>', $html );
    }
}

phpunit を実行します。

$ phpunit
Installing...
Running as single site... To run multisite, use -c tests/phpunit/multisite.xml
Not running ajax tests. To execute these, use --group ajax.
Not running ms-files tests. To execute these, use --group ms-files.
Not running external-http tests. To execute these, use --group external-http.
PHPUnit 5.6.0 by Sebastian Bergmann and contributors.
.F                                                                  2 / 2 (100%)
Time: 1.36 seconds, Memory: 26.00MB
There was 1 failure:
1) TwitterShortcodeTest::test_twitter_shortcode
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'<a href="https://twitter.com/driftwoodjp">@driftwoodjp</a>'
+'[twitter]@driftwoodjp[/twitter]'
/var/www/html/wp-content/plugins/sandbox-hatamoto/tests/test-twitter-shortcode.php:11
FAILURES!
Tests: 2, Assertions: 2, Failures: 1.

コードを書く

wordpress/wp-content/plugins/sandbox-hatamoto/sandbox-hatamoto.php
add_shortcode( 'twitter', 'twitter_shortcode' );
function twitter_shortcode( $p, $content ) {
    $content = str_replace( "@", '', $content );
    if ( !preg_match( "/^[0-9a-z_]{1,15}$/i", $content ) ) {
        return;
    }
    return sprintf(
        '<a href="https://twitter.com/%s">@%s</a>',
        esc_attr( $content ),
        esc_html( $content )
    );
}

phpunit を実行します。

$ phpunit
Installing...
Running as single site... To run multisite, use -c tests/phpunit/multisite.xml
Not running ajax tests. To execute these, use --group ajax.
Not running ms-files tests. To execute these, use --group ms-files.
Not running external-http tests. To execute these, use --group external-http.
PHPUnit 5.6.0 by Sebastian Bergmann and contributors.
..                                                                  2 / 2 (100%)
Time: 1.32 seconds, Memory: 26.00MB
OK (2 tests, 3 assertions)