這邊練習 PHPUnit 測試的撰寫,依序創建Controller、Service。
首先創建一個名為 IndexAction 的 Single Actions Controller
Single Actions Controller
方便我們處理複雜的作業,且也可以避免Controller肥大的問題。
php artisan make:controller IndexAction --invokable
如果使用 Single Actions Controller,則路由檔可以減少寫對應的 action
use App\Http\Controllers\IndexAction;
Route::post('/calculator', IndexAction::class);
創建Controller完畢後,建立一個呼叫Calculator Serivce 來計算兩數字處理,程式碼如下:
<?php
namespace App\Http\Controllers;
use App\Services\Calculator;
use Illuminate\Http\Request;
class TestController extends Controller
{
private Calculator $myCalculator;
public function __construct(Calculator $myCalculator)
{
$this->myCalculator = $myCalculator;
}
public function getCalculatorResult()
{
$result = $this->myCalculator->calculator('Addition', 1, 2);
return $result;
}
}
接著創建名為Calculator Service,並寫一個計算的邏輯,這邊定義一個計算類型$operation
,根據要計算的方式處理
<?php
namespace App\Services;
Class Calculator
{
public function calculator(string $operation, int $a, int $b)
{
//加法 Addition
//減法 Subtraction
//乘法 Multiplication
switch($operation){
case 'Addition':
$reuslt = $a + $b;
break;
case 'Subtraction':
$reuslt = $a - $b;
break;
case 'Multiplication':
$reuslt = $a * $b;
break;
default:
return 'The operation is not suported.';
}
return $reuslt;
}
}
接著撰寫Service單元測試,這邊要測試 Service calculator function,並確保傳入值都有如實測試到,這邊使用 data-providers 幫助我們建立多個測試類型,依序測試加法、減法、乘法及未提供 Operation type
<?php
namespace Tests\Unit;
use App\Services\Calculator;
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase
{
protected $calculator;
public function setUp(): void
{
$this->calculator = $this->createMock(Calculator::class);
}
/**
* @dataProvider dataProvider
* @param string $operation
* @param int $a
* @param int $b
* @param mixed expectResult
*/
public function test_calculator(string $operation, int $a, int $b, mixed $expectResult)
{
$calculatorResult = new Calculator($this->calculator);
$this->assertEquals($expectResult, $calculatorResult->calculator($operation, $a,$b));
}
public static function dataProvider()
{
return [
'Addition' => ['Addition', 1, 2, 3],
'Subtraction' => ['Subtraction', 2, 1, 1],
'Multiplication' => ['Multiplication', 2, 2, 4],
'no Operation' => ['', 0, 0, 'The operation is not suported.']
];
}
}
接著執行測試,一般可以使用php artisan test
進行測試。
或是對單一檔案測試
// 對單一檔案進行測試
php artisan test Tests/Unit/CalculatorTest.php
測試單一檔案其中某個 testing function
php artisan test Tests/Unit/CalculatorTest.php --filter test_calculator
接著可以看到測試結果
總結:以上是單元測試練習過程,下一部分將以整合測試繼續說明
不知道為何範例程式碼明明編輯時內容是有排版,但發布後空白都消失了XD
參考文件