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?

PHP Laravel テストコードUnit

Last updated at Posted at 2025-12-02

テストコード Unit

  • Unitとはプログラムを構成する最小単位を表す
  • laravelでは単一のメソッド単一のクラスであることが多い
  • unitテストでは外部の要因(データベースやAPIなど)を一切使用せず、外部に依存している部分はモック(テスト用のデータ)に置き換えられる

基本構造

  • Arrange(準備) テストに必要なデータや環境を用意する
  • Act(実行) テスト対象のメソッドや関数を実際に呼び出す
  • Assert(検証) 実行結果が期待通りかチェックする

Arrenge

  • テスト対象のインスタンス化
  • 入力データの定義
  • 期待値の定義

// テスト対象のインスタンス化
$calculator = new PriceCalculator();

// 入力データの定義
$basePrice = 1000;
$discountRate = 0.5; 

// 期待値の定義 (結果は550円になるはず)
$expected = 550;

 

Act

  • 実際の処理
  • 結果の格納

// テスト対象のメソッドを実行し、実際の結果($actual)を取得
$actual = $calculator->calculateFinalPrice($basePrice, $discountRate);

 

Assert

  • アサーションの実行

// 期待値($expected)と実際の値($actual)が一致するか検証
$this->assertEquals($expected, $actual);

 

テストの実行

php artisan testをターミナルで実行

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?