Codeceptionを使ってみた(1) 導入

個人的に大注目しているPHP用のテスティングフレームワーク

Codeception - BDD-style PHP testing.

を試しています。
まだ日本語情報が少ないですが、以下のコードを見て一発で気に入ってしまいました。

<?php 
$I->am('testing framework');
$I->wantToTest('your web application');
$I->see('it works!');

Codeceptionってなに?

特徴としては、

といったところでしょうか。

2013/7/8時点の最新バージョンは1.6.3.1、活発に開発も行われています。

このエントリからではCodeceptionの導入編として、

  • インストール&起動方法
  • 基本的なテストの書き方

を紹介してみます。

たぶん長くなるので、適当に分割します。

0. 前提情報

1. インストール

基本的には Quick Start Codeception を参照すればOKと思いますが、私はComposerを利用しました。

1.1. Composerの取得

Composer に倣って。

C:\workspace\proj> php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));"
#!/usr/bin/env php
All settings correct for using Composer
Downloading...

Composer successfully installed to: C:\workspace\composer.phar
Use it: php composer.phar

1.2. Composerでプロジェクトを初期化

C:\workspace\proj> php .\composer.phar init

1.3. Codeceptionを依存関係に追加

C:\workspace\proj> php .\composer.phar require --dev codeception/codeception 1.6.*

vendorディレクトリ配下に依存パッケージが追加されます。
また、cliコマンドはvender/binディレクトリにインストールされます。
Codeceptionは「内部ではPHPUnitを利用」している、と書いたとおり、
vendor/bin配下には

の両方のCLIコマンドがあることがわかります。

1.4. 動作確認

C:\workspace\proj> vendor\bin\codecept.bat

として、バージョン番号やUsageが表示されればOKです。

2. テストの初期化

C:\workspace\proj>vendor\bin\codecept.bat bootstrap

Initializing Codeception in C:\workspace\proj

File codeception.yml created <- global configuration
tests/unit created <- unit tests
tests/functional created <- functional tests
tests/acceptance created <- acceptance tests
tests/unit.suite.yml written <- unit tests suite configuration
tests/functional.suite.yml written <- functional tests suite configuration
tests/acceptance.suite.yml written <- acceptance tests suite configuration
Building initial Guy classes
Building Guy classes for suites: acceptance, functional, unit
WebGuy includes modules: PhpBrowser, WebHelper
WebGuy.php generated successfully. 45 methods added
TestGuy includes modules: Filesystem, TestHelper
TestGuy.php generated successfully. 11 methods added
CodeGuy includes modules: CodeHelper
CodeGuy.php generated successfully. 0 methods added

Bootstrap is done. Check out C:\workspace\proj/tests directory

プロジェクトのルート配下に

  • codeception.yml
  • testsディレクトリ

が作成されます。

さらにtestsディレクトリ配下には

  • acceptance(受入テスト)
  • functional(機能テスト)
  • unit(単体テスト

のそれぞれのYML設定ファイルおよびテストを格納するディレクトリ、またログ出力ディレクトリ等が作成されます。
ちなみに、Codeceptionでは「acceptance」や「functional」など、を「test suite」と呼び、任意のtest suiteを作成することも可能です。
参考:Codeception Commands

Guyって?

上の出力で、

  • WebGuy
  • TestGuy
  • CodeGuy

というものがありますが、これは、

One of the main concepts of Codeception is representation of tests as actions of a person. We call this person a Guy.

http://codeception.com/docs/02-GettingStarted

だ、そうです。
BDDの特徴の一つとして、より「自然言語に近い」形でテストを記述する、というものがありますが、これを支えているのが「Guy」達なんですね。
実際には「Guy」に「$I」という変数名を与えることで

$I->wantTo("test web application");

みたいなコードを記述することが可能となります。


いったん、以上です。
次回FizzBuzz問題を題材にテストを書いてみます。