0
0

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 1 year has passed since last update.

Laravelテストのメモ

Posted at

Laravel+PHPUnitのテストについてのメモ。

なお、Laravel5系をベースにしたプログラムなので一部いまと違うかも。。

基本的な形

<?php

use App\Models\User;
use Carbon\Carbon;
use Tests\TestCase;

class SampleTest extends TestCase
{
    /**
     * @test
     */
    public function サンプルのテスト()
    {
        $user = factory(User::class)->states('active')->create([
            'last_login_at' => Carbon::yesterday()
        ]);

        $response = $this->actingAs($user)
            ->json('get', route('users.me.get'));

        $response->assertSuccessful();

        $decodedResponse = $response->json('user');
        $this->assertSame($user->id, $decodedResponse['id']);
    }
}

例外エラーチェック

<?php

use Illuminate\Validation\UnauthorizedException;
use Tests\TestCase;

class SampleTest extends TestCase
{
    /**
     * @test
     */
    public function 例外エラーの確認()
    {
        $this->expectExceptionObject(new UnauthorizedException('認証エラー'));

        $response = $this->json('get', route('users.me.get'));
    }
}

実行する前に expectExceptionObject で発生する例外を定義しておく。

テストスキップ

<?php

use Tests\TestCase;

class SampleTest extends TestCase
{
    /**
     * @test
     */
    public function なんかのテスト()
    {
        $this->markTestSkipped('SKIP');

        $this->expectExceptionObject(new UnauthorizedException('認証エラー'));

        $response = $this->json('get', route('users.me.get'));
    }
}

markTestSkipped を入れるとテストがスキップされる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?