我們平常寫完程式碼後,為了確認自己寫的無誤,以往都是打開網頁實際操作一遍畫面,確認無誤後就把功能直接上線。但這樣其實會有些問題:
為了測試一個小功能,做了一大堆操作,浪費時間
出現 Bug 了!但很難找 Bug 藏在哪
假如是「從前端測試 API 功能」,因為 Bug 可能出現在前端也有可能在後端,用這種方式找很難第一時間找到錯誤點
async function httpGetPosts() {
const response = await axios.get('/posts') // 如果發生 error 了,你有辦法第一時刻找出問題在前端還是後端嗎
}
假如用 Postman 測試後端,這會把整個 method 跑過一遍,但你可能只想測其中一小段程式碼而已
/*
* 假如我們實作一個新增文章的功能
*/
function insert(Request $request)
{
# insert data into database
$data = $request->data;
$this->storeIntoDB($data);
# store file in storage
$file = $request->file;
$this->storInfoFolder($file); // 例如我只是想測試這個函式是否有誤,跑完整個 method 不太實際
# update some state in other table
$user = $request->user();
$this->updateState($user);
}
我改了部份程式碼後,同樣會用到這段程式碼的舊碼突然就不能跑了!
例如在 UserController 跟 PostController 都有用到一個共用的 function:getDate(),你可能修改它之後導致其中一個 controller 壞掉,可是你沒發覺。
// in UserController.php
use App\\Services\\DateService;
class UserController
{
// 略...
public function show()
{
$date = $this->DateService->getDate();
// 略...
}
// 略...
}
// in PostController.php
use App\\Services\\DateService;
class PostController
{
// 略...
public function allPosts()
{
$date = $this->DateService->getDate();
// 略...
}
// 略...
}
為了解決上述的問題而開始有了應該要來寫測試碼的風氣。不過,什麼是測試?