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

memo.

[markdown]
「[WordPress プラグインのユニットテスト環境を作る](https://www.d-wood.com/blog/2017/07/27_9129.html)」の続き。写経。

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

## テストを書く

“`php:wordpress/wp-content/plugins/sandbox-hatamoto/tests/test-twitter-shortcode.php
assertEquals( ‘@driftwoodjp‘, $html );
// without @
$html = do_shortcode( ‘[twitter]driftwoodjp[/twitter]’ );
$this->assertEquals( ‘@driftwoodjp‘, $html );
}
}
“`

`phpunit` を実行します。

“`prettyprinted
$ 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
@@ @@
-‘@driftwoodjp
+'[twitter]@driftwoodjp[/twitter]’
/var/www/html/wp-content/plugins/sandbox-hatamoto/tests/test-twitter-shortcode.php:11
FAILURES!
Tests: 2, Assertions: 2, Failures: 1.
“`

## コードを書く

“`php: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(
@%s‘,
esc_attr( $content ),
esc_html( $content )
);
}
“`

`phpunit` を実行します。

“`prettyprinted
$ 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)
“`
[/markdown]