使用 mmock 去 Mock API,會需要放置 mock 的設定。

設定檔可以是 json 格式…

{ “request”: { “method”: “GET”, “path”: “/hello/*” }, “response”: { “statusCode”: 200, “headers”: { “Content-Type”:[“application/json”] }, “body”: “{"hello": "{{request.query.name}}, my name is {{fake.FirstName}}"}” } }

也可以是 yml 格式…


request: method: GET path: “/hello/*” response: statusCode: 200 headers: Content-Type:

  • application/json body: ‘{“hello”: “{{request.query.name}}, my name is {{fake.FirstName}}”}’

設定檔格式定義如下:

{ “description”: “Some text that describes the intended usage of the current configuration”, “request”: { “host”: “example.com”, “method”: “GET|POST|PUT|PATCH|…”, “path”: “/your/path/:variable”, “queryStringParameters”: { “name”: [“value”], “name”: [“value”, “value”] }, “headers”: { “name”: [“value”] }, “cookies”: { “name”: “value” }, “body”: “Expected Body” }, “response”: { “statusCode”: “int (2xx,4xx,5xx,xxx)”, “headers”: { “name”: [“value”] }, “cookies”: { “name”: “value” }, “body”: “Response body” }, “control”: { “scenario”: { “name”: “string (scenario name)”, “requiredState”: [ “not_started (default state)”, “another_state_name” ], “newState”: “new_stat_neme” }, “proxyBaseURL”: “string (original URL endpoint)”, “delay”: “int (response delay in seconds)”, “crazy”: “bool (return random 5xx)”, “priority”: “int (matching priority)”, “webHookURL” : “string (URL endpoint)” } }

主要分為 Request、Response、與 Control 幾塊。

Request 這塊是用來描述 http 請求的,像是請求的主機、http method、請求的路徑位置、請求的參數、請求的標頭、cookie、及請求的內容。

ElementDescription
hostRequest http hostt. (without port)
methodRequest http method.
pathResource identifier. It allows :value matching. Mandatory
queryStringParametersArray of query strings. It allows more than one value for the same key.
headersArray of headers. It allows more than one value for the same key.
cookiesArray of cookies.
bodyBody string. It allows * pattern.

Response 部分用來描述 http 的回應,像是回應的狀態碼、回應的標頭、cookie、及回應的內容。

ElementDescription
statusCodeRequest http method.
headersArray of headers. It allows more than one value for the same key and vars.
cookiesArray of cookies. It allows vars.
bodyBody string. It allows vars.

Control 部分不一定需要,用來做些控制使用的,像是回應的延遲時間、是否隨機回應錯誤…等。

ElementDescription
scenarioA scenario is essentially a state machine whose states can be arbitrarily assigned.
proxyBaseURLIf this parameter is present, it sends the request data to the BaseURL and resend the response to de client.
delayDelay the response in seconds. Simulate bad connection or bad server performance.
crazyReturn random server errors (5xx) in some request. Simulate server problems.
prioritySet the priority to avoid match in less restrictive mocks. Higher, more priority.
webHookURLAfter any match if this option is defined it will notify the match to the desired endpoint.