0
0

More than 3 years have passed since last update.

Laravel ユニットテスト用メソッド

Last updated at Posted at 2020-05-03

前提

Laravelのテスト用メソッドについてメモしていきます。

本題

ステータスのチェック

$this->get('/')->assertStatus(200);

ステータスOKのチェック

$this->get('/hello')->assertOk();

POSTのチェック

$this->post('/hello')->assertOk();

パラメータを指定する

$this->get('/hello/1')->assertOk();

存在しないページのチェック

$this->get('/hoge')->assertStatus(404);

※用意していないアドレスを指定し、ステータスコードが404かどうかをチェック。
不用意に「存在しないはずのページにアクセスできてしまう」といったことを確認できる。

コンテンツに含まれるテキスト

$this->get('/hello')->assertSeeText('Index');

レスポンスに含まれるテキスト

$this->get('/hello')->assertSee('<h1>');

用意したテキストが順に登場する

$this->get('/hello')->assertSeeInOrder(['<html','<head','<body','<h1>']);

Ajaxへのアクセス

$this->get('/hello/json/1')->assertSeeText('YAMADA-TARO');

Ajaxの内容チェック

$this->get('/hello/json/2')->assertExactJson(
          ['id'=2, 'name'=>'HANAKO',
          'mail'=>'hanako@flower','age'=>'19']);

各テスト後のデータベースリセット

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    use RefreshDatabase; #この記述でリセット可能

    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function testBasicExample()
    {
        $response = $this->get('/');

        // …
    }
}
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