LoginSignup
8
7

More than 5 years have passed since last update.

Codeceptionでエンドツーエンドテストする

Posted at

Codeception

インストール、導入は割愛。
APIを想定して、レスポンスJSONのテスト。
"テスト実行まで"とcest形式、初期処理、後処理の実行についてなどを説明します。

テスト実行まで

テスト実行までの手順は以下になります。

  1. スイート生成
  2. .yml設定
  3. クラス生成
  4. テスト実行

スイート生成

php codecept.phar generate:suite {suite_name}

% php codecept.phar generate:suite api

.yml設定

以下のようにPhpBrowser, REST, ApiHelperをenableにして、エンドポイントURLを設定します。

class_name: ApiTester
modules:
    enabled: [PhpBrowser, REST, ApiHelper]
    config:
        PhpBrowser:
          url: 'http://example.com/'
        REST:
           url: 'https://example.com/v1/'

クラス生成(cest形式)

php codecept.phar generate:cest {suite_name} {cest_name}

% php codecept.phar generate:cest api People

テスト実行

php codecept.phar run {suite_name}

%php codecept.phar run api

個別にデバッグ

php codecept.phar run --debug {suite_name} {class_name}

% php codecept.phar run --debug api PeopleCest.php

cest形式

1つのクラスとしてテストケースを書くことが出来ます。

生成された直後のファイルは以下になります。
tryToTestはテスト実行時に1回呼ばれるメソッドで、_before,_afterは各メソッドが呼ばれる度に実行されます。

_beforeは初期処理、_afterは後処理となっておりsend前と後に実行されます。

BasicCest.php
<?php
class BasicCest
{
    public function _before(\AcceptanceTester $I)
    {
    }

    public function _after(\AcceptanceTester $I)
    {
    }

    // tests
    public function tryToTest(\AcceptanceTester $I) 
    {    
    }
}
?>

抜粋 http://codeception.com/docs/07-AdvancedUsage

テストクラス

PeopleCest.php
    public function post(ApiTester $I)
    {
        $I->wantTo('POST Test');
        $id   = 1;
        $data = array("name"=> "taro", "age" => 17);

        $I->sendPOST('people/'.$id, json_encode($data));

        $I->seeResponseContainsJson(array('result'=>0));
        $I->seeResponseJsonMatchesJsonPath('$.response.result');
    }
  • エンドポイント:'people/1'
  • リクエストボディ:{"name":"name","age":17}

POST送信して、

  • レスポンスボディ:{"response":{"result":0}}

であることをテストしています。

共通の初期処理、後処理を定義する

共通処理クラスを作る

TestCommons.php
<?php
class TestCommons
{
    public static function defaultHaveHttpHeader(ApiTester $I)
    {
        $I->haveHttpHeader('Content-Type', 'application/x-www-form-urlencoded');
        $I->haveHttpHeader('DebugFlag', 1);
    }

    public static function commonSee(ApiTester $I)
    {
        $I->seeResponseCodeIs(200);
        $I->seeResponseIsJson();
    }
}

_bootstrapに定義

_bootstrap.php
<?php
require_once __DIR__.'/TestCommons.php';

テストクラスで呼び出す

    public function _before(ApiTester $I)
    {
        TestCommons::defaultHaveHttpHeader($I);
    }

    public function _after(ApiTester $I)
    {
        TestCommons::commonSee($I);
    }

とっても簡単にエンドツーエンドなテストが行えます。

8
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
8
7