1
1

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 5 years have passed since last update.

テストコードを書いてみよう

Last updated at Posted at 2019-11-02

テストコード

LaravelにはPHPを代表するテストフレームワークの「PHPunit」が同梱されている他、ブラウザを使った自動操作が可能な「Laravel Dusk」など、開発者のテストを支援する機能が備わっている。

ここでは「PHPunit」の説明をします。

準備

/homeにアクセスした際、「こんにちは」と表示されるviewファイルを作成してください。


テストコードファイルを作成する。


$ php artisan make:test HomeTest

Test created successfully.

tests/FeatureディレクトリにHomeTest.phpが作成される。

テストコードを書きましょう!


<?php

namespace Test\Feature;

use Tests\TestCase;

class HomeTest extends TestCase
{
  public function testStatusCode()
  {
    $response = $this->get('/home');
    $response -> assertStatus(200);
  }

  public function testBody(){

    $response = $this->get('/home');

    $response-> assertSeeText("こんにちは");
  }
}
 ?>

こんな感じです。
TestCaseを継承して作成されます。

また、テストメソッドの名前は先頭に「Test」を付与します。


今回実行するテスト内容は?

testStatusCodeがステータスコード200を確認するメソッド
※ステータスコード200とは、クライアントからのリクエストが受付に成功した時の番号です

testBodyがレスポンスに文字列「こんにちは」を含むことを確認するメソッド

です。

テストするviewファイル(blade.php)は



<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    こんにちは!
  </body>
</html>

実行していきましょう!

コマンドは
vendore/bin/phpunitです。
引数に対象のテストクラスファイルを指定します。
指定しない場合はtestフォルダ以下の全てのテストファイルが実行されます。
用途によって使い分けましょう!

$ vendor/bin/phpunit tests/Feature/HomeTest.php
PHPUnit 6.5.14 by Sebastian Bergmann and contributors.

..                                                                  2 / 2 (100%)

Time: 90 ms, Memory: 12.00MB

OK (2 tests, 2 assertions)

最後に「OK(2 tests,2assertions)」と表示されれば、トップ画面のテストをクリアしています!

テスト結果はRedとGreenで分けられます。Greenであれば異常なし!ということですね。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?