為何需要使用到Mock?
可參考這篇[面試][後端]在正式 API 完成前,如何讓要串接的工程師不要空等?
不只是前端可能會遇到要等後端API完成,有時候後端要與其他Server對接API拿資料時,也會使用到。
當不只是一個部門再開發時,可能需要與其他部門合作,等待對接API資料時,也能有效提高開發速度,避免在那等來等去的。
Table of Contents
<span class="ez-toc-title-toggle"><a href="#" class="ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle" aria-label="顯示/隱藏內容目錄"><span class="ez-toc-js-icon-con"><span class=""><span class="eztoc-hide" style="display:none;">Toggle</span><span class="ez-toc-icon-toggle-span"><svg style="fill: #999;color:#999" xmlns="http://www.w3.org/2000/svg" class="list-377408" width="20px" height="20px" viewBox="0 0 24 24" fill="none"><path d="M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z" fill="currentColor"></path></svg><svg style="fill: #999;color:#999" class="arrow-unsorted-368013" xmlns="http://www.w3.org/2000/svg" width="10px" height="10px" viewBox="0 0 24 24" version="1.2" baseProfile="tiny"><path d="M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z"/></svg></span></span></span></a></span>
建立 Mock Server


建議勾選儲存 mock server URL 到環境變數的選項。
創建成功左方會新增一個Mock及mock server URL
點擊左方的Environments會有剛才建立的Mock Server Name,會自動將mock server URL帶入到url內,
後續只要打{{url}}就會取得資訊。
設計 Mock Server Response
- 到Collections的分頁
- 找到剛剛初始化的 Request,{{url}}會自動帶入
- 環境變數右上角請選擇剛剛建立的「User」
- 按下Send後
- 下面的Response一片空白是正常的,因為還沒設定 Mock Server Response

左側 Request 下面有一個「Default」,它就是用來自訂Response example,
最下方改為Json輸入完後儲存:
{
"id":1,
"user": "bocky"
}
回到Request,按下Send後,Response會跟剛剛填寫Json相同:
response 給隨機資料
Postman 本身就有提供給隨機資料的參數,主要在 example response 那邊把固定值改填參數就行,在 文件 中給的範例是這樣:
{
"name": "{{$randomFullName}}",
"userName": "{{$randomUserName}}",
"location": "{{$randomCity}}",
"company": "{{$randomCompanyName}}",
"jobTitle": "{{$randomJobTitle}}",
"updatedAt": "{{$timestamp}}"
}收到的 response 就會像這樣:
{
"name": "Mrs. Dana Berge",
"userName": "Natalie.Moen85",
"location": "South Orlando",
"company": "Bergstrom, Schultz and O'Conner",
"jobTitle": "Forward Data Manager",
"updatedAt": "1674070363"
}Postman 有的隨機參數官方都整理在這:Dynamic variables
依狀況返回不同的Response
通常在不同狀況會有不同的Response,例如成功或失敗。
成功/失敗的返回方式
再新增一個Explore為失敗的UserNume(success)。
當data為success時,返回:
{
"status": "success",
"msg": "成功",
"data": {
"name": "{{$randomFullName}}",
"userName": "{{$randomUserName}}",
"location": "{{$randomCity}}",
"company": "{{$randomCompanyName}}",
"jobTitle": "{{$randomJobTitle}}",
"updatedAt": "{{$timestamp}}"
}
}
再新增一個Explore為失敗的UserNume(Error)。
當data為error時的Response為
{
"status": "error",
"msg": "失敗",
"data": {}
}
測試成功Response:
測試失敗的Response: