この記事はCodeIgniter Advent Calendar 2016の16日目です。
概要
業務でレガシーなPHPアプリケーションを運用しており、改善のためにScrutinizer CIを導入しています。
Scrutinizer CIはソースコードの静的解析がメインの機能ですが、ユニットテストの実行もサポートしており、一番安いベーシックプランから利用できます。
導入までに何箇所か躓いたので、備忘録のために残します。
前提
- GitHubでコードを管理している
- Scrutinizer CIにリポジトリを登録している
- Codeigniter 2.0.3を利用している
CIUnitをインストール
CIUnitはCodeigniterでPHPUnitを使うためのツールです。
以下のURLにCodeigniter 2.0.3へのCIUnitのインストール方法が詳しく説明されています。
http://d.hatena.ne.jp/Kenji_s/touch/20110905/1315190819
Scrutinizer CIで任意のPHPバージョンをインストール
任意のバージョンのPHPでアプリケーションを実行したい場合は、settings->configurationで以下の設定を追記します。
2017/01/27時点で、5.4.41からサポートしています。
build:
environment:
php: 7.0.6
参照:https://scrutinizer-ci.com/docs/build/environment
PHPUnitをインストール(Composer)
リポジトリにcomposer.jsonがあると、自動的にcomposer install
を実行してくれるので便利です。
Composerを使ってのPHPUnitのインストール方法は以下にあります。
https://phpunit.de/manual/4.8/ja/installation.html#installation.composer
phpunit.xmlを作成
./vendor/bin/phpunit
でユニットテストが実行できるように、以下のような設定ファイルを用意します。
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.5/phpunit.xsd"
colors="true"
backupGlobals="false"
backupStaticAttributes="false"
stopOnFailure="false"
bootstrap="./applications/third_party/CIUnit/bootstrap_phpunit.php">
<filter>
<whitelist>
<directory>./applications/</directory>
<exclude>
<directory>./applications/third_party/</directory>
<directory>./applications/views/</directory>
</exclude>
</whitelist>
</filter>
<testsuites>
<testsuite name="ControllerTests">
<directory suffix=".php">./tests/controllers/</directory>
</testsuite>
<testsuite name="HelperTests">
<directory suffix=".php">./tests/helpers/</directory>
</testsuite>
<testsuite name="LibTests">
<directory suffix=".php">./tests/libs/</directory>
</testsuite>
<testsuite name="ModelTests">
<directory suffix=".php">./tests/models/</directory>
</testsuite>
<testsuite name="SystemTests">
<directory suffix=".php">./tests/system/</directory>
</testsuite>
</testsuites>
</phpunit>
Scrutinizer CIでユニットテスト実行の設定をする
settings->configurationで以下の設定を追記します。
build:
environment:
timezone: 'Asia/Tokyo' # デフォルトUTC
tests:
override:
-
command: './vendor/bin/phpunit --coverage-clover=.coverage.xml'
coverage:
file: '.coverage.xml'
format: 'clover'
idle_timeout: 600 # タイムアウトの設定*
- 適宜変更してください。
まとめ
- データベースが関連するテストなどは、もう少し複雑な設定が必要と思います。
- とりいそぎ、libraryやhelperなどの、外部APIとの関連がないクラスをテストしたい場合は、サクッと設定できて幸せになれます。
- 長期的にソースコードを保守しなければならない場合、ソースコードの劣化に早く気づけるようなツールは必須ですので、やってみてください。
- そのほか、指摘等あればお願いします。