PHPUnit + Laravel = ? API試験の話

まいどー わしです!

今日はざっくりしたAPIの試験をLaravelとPHPUnitで書いてみたいと思います。

APIってみんな、大好きやんw
さてさて、おまじないとか一切吹っ飛ばして

今回の作るAPIは激烈シンプルなechoです。

つまりはメッセージ送ったら返すってだけです。
TDDなので先に試験を書きます!

<?php

namespace Tests\Feature;

use Tests\TestCase;

class EchoControllerTest extends TestCase
{
    public function testExample()
    {
        $response = $this->get('/api/echo');

        $response->assertStatus(200)
            ->assertJson(['status'=>'OK','message'=>'']);
    }
    public function test_echo_get(){
        $response = $this->get('/api/echo?message=hello')
            ->assertStatus(200)
            ->assertJson(['status'=>'OK','message'=>'hello']);
    }

    public function test_echo(){
        $response = $this->post('/api/echo',['message'=>'hello'])
            ->assertStatus(200)
            ->assertJson(['status'=>'OK','message'=>'hello']);
    }
}

この中でのポイントは、testExampleでAPIの存在を確認していて、test_echo_getでGETリクエストでの回答をチェック
test_echoでPOSTリクエストをチェックしいています

はい、POST / GET対応版です。

次に、ルートというかapi.php

Route::any('echo','EchoController@echo');

うん、説明が難しいくらいの内容です…

で、できあがりのソース!

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class EchoController extends Controller
{
    function echo(Request $request){
        $response = [];
        $response['status'] = "OK";
        $response['message'] = $request->input('message','');

        return response()->json($response);
    }
}

… そうなるわなw

シンプルでしょ、別にserveさせなくても動作しますのでCIでも問題ないのが良いね。

次は… ってちょっとだけLeravel Duckをみているけどちょっとだけ複雑になるかな?

class ExampleTest extends DuskTestCase
{
    public function testBasicExample()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/simple')
                    ->assertSee('Simple')
                    ->clickLink('here')
                    ->assertSee('Google')
                    ->screenshot('ok');

        });
    }
}

この程度でsampleのページに貼ったgoogleリンクを辿ってくれます。
こいつは仮想ブラウザなのでwebサーバを上げておかないとダメなのがネックかな。そうなってくるとSeleniumでも良いかも… とか思っているけど下にあるContinous Integrationが気になっている…

そんな浮気心乙女心でした。次回も頑張るよ!またねっ!
※ ソースの前に記事をTDDしなさい