6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WordPressと外部サービスのAPIを連携させるプラグインのユニットテストの方法

Last updated at Posted at 2016-03-02

概要

WordPressで外部サービスと連携する際のユニットテストのやり方の紹介です。

https://github.com/megumiteam/woocommerce-elasticsearch

今回WooCommerceの商品検索や関連商品をElasticseachで代替する機能を作るためのcomposerライブラリを作ったのですが、そこでElasticseachのエンドポイントと接続してユニットテストを行っていますので、これを元に紹介していきたいと思います。

PHPUnitのコード

ElasticsearchのエンドポイントをPHPUnit実行時に外部から引き渡すようにしてあげます。
なので外部からの引数をテストコード内で受け取るようにして上げる必要があります。
ES_HOST=‘example.com’ ES_PORT=‘9200’ phpunit

プラグインはwp scaffold pluginで作成します。
そしてユニットテストの初期化処理を行っているtests/bootstrap.phpに以下の用に手を加えます。

function _manually_load_plugin() {
	
	$host = getenv( 'ES_HOST' );
	$host = preg_replace( '/(^https:\/\/|^http:\/\/)/is', '', $host );
	$port = getenv( 'ES_PORT' );
	if ( empty( $host ) ) {
		$host = 'localhost';
	}
	if ( empty( $port ) ) {
		$port = 9200;
	}
	define( 'ES_HOST', $host );
	define( 'ES_PORT', $port );

これで上の例ではES_HOSTES_PORTが定数としてユニットテスト内で使えます。
あとはユニットテストの中で引数を元にテストを書いてあげればOKです。

Travisで実行

Travisでテストする時はさすがに外部から値を渡す方法が思いつかなかったので、TravisにElasticsearchをインストールしてhttp://localhost:9200 をエンドポイントとしてテストを実施します。

https://docs.travis-ci.com/user/database-setup/
TravisではElasticsearchが予め使えるようにインストール済みです。

.travis.ymlに以下を記述するだけでElasticsearchを立ち上げてくれます。

services:
  - elasticsearch

特にPHPUnitの実行時に引数を与えなければ、http://localhost:9200 に接続してテストを回すようにtests/bootstrap.phpでコードを記述します。

https://travis-ci.org/megumiteam/woocommerce-elasticsearch

するとこんな感じでTravisでテストもできちゃいます。

ただこれだとTravisのローカルにインストールできるものでしかテストが出来ません。AWSリソースと接続してテストを行う場合のテストはどうしようかなって感じです。

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?