# Mocking

`mocking` 插件允许你模拟 API 响应，而无需将请求转发到上游服务。该插件支持自定义响应状态码、响应体、响应头等。这在开发、测试或调试阶段特别有用，因为在这些阶段，实际的上游服务可能不可用、正在维护或调用成本高昂。通过以预定义格式提供模拟响应，该插件使你能够测试客户端集成、验证请求处理并调试问题，而无需依赖上游基础设施。

## 示例[​](#示例 "示例的直接链接")

以下示例演示了如何在不同场景下配置 `mocking` 插件。

### 生成特定的模拟响应[​](#生成特定的模拟响应 "生成特定的模拟响应的直接链接")

以下示例演示了如何配置插件以生成特定的模拟响应和响应状态码，而不将请求转发到上游服务。

创建一个使用 `mocking` 插件的路由，并为预期的模拟响应定义响应体：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "mocking-route",

    "uri": "/anything",

    "plugins": {

      "mocking": {

        "response_status":201,

        "response_example":"{\"Lastname\":\"Brown\",\"Age\":56}"

      }

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    routes:

      - name: mocking-route

        uris:

          - /anything

        plugins:

          mocking:

            response_status: 201

            response_example: '{"Lastname":"Brown","Age":56}'

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，并确认变更仅影响本指南使用的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=mocking
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=mocking
```

* Gateway API
* APISIX CRD

mocking-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: mocking-plugin-config

spec:

  plugins:

    - name: mocking

      config:

        response_status: 201

        response_example: '{"Lastname":"Brown","Age":56}'

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: mocking-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: mocking-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将配置应用到集群：

```
kubectl apply -f mocking-ic.yaml
```

mocking-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Domain

    name: httpbin.org

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: mocking-route

spec:

  ingressClassName: apisix

  http:

    - name: mocking-route

      match:

        paths:

          - /anything

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: mocking

        enable: true

        config:

          response_status: 201

          response_example: '{"Lastname":"Brown","Age":56}'
```

将配置应用到集群：

```
kubectl apply -f mocking-ic.yaml
```

❶ 配置预期的模拟响应状态码为 `201`。

❷ 配置预期的模拟响应体为 `{"Lastname":"Brown","Age":56}`。

发送请求到路由：

```
curl -i "http://127.0.0.1:9080/anything"
```

你应该收到 `HTTP/1.1 201 Created` 模拟响应，并看到以下响应体：

```
{"Lastname":"Brown","Age":56}
```

### 生成模拟响应头[​](#生成模拟响应头 "生成模拟响应头的直接链接")

以下示例演示了如何配置插件以生成模拟响应头，并在响应体中使用[内置变量](https://docs.apiseven.com/apisix/reference/built-in-variables.md)。

创建一个使用 `mocking` 插件的路由，定义预期的模拟响应的响应头和响应体：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "mocking-route",

    "uri": "/anything",

    "plugins": {

      "mocking": {

        "response_headers": {

          "X-User-Id": 100,

          "X-Product-Id": "apac-398-472"

        },

        "response_example":"Client IP: $remote_addr"

      }

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    routes:

      - name: mocking-route

        uris:

          - /anything

        plugins:

          mocking:

            response_headers:

              X-User-Id: 100

              X-Product-Id: apac-398-472

            response_example: "Client IP: $remote_addr"

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，并确认变更仅影响本指南使用的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=mocking
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=mocking
```

* Gateway API
* APISIX CRD

mocking-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: mocking-plugin-config

spec:

  plugins:

    - name: mocking

      config:

        response_headers:

          X-User-Id: 100

          X-Product-Id: apac-398-472

        response_example: "Client IP: $remote_addr"

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: mocking-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: mocking-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将配置应用到集群：

```
kubectl apply -f mocking-ic.yaml
```

mocking-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Domain

    name: httpbin.org

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: mocking-route

spec:

  ingressClassName: apisix

  http:

    - name: mocking-route

      match:

        paths:

          - /anything

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: mocking

        enable: true

        config:

          response_headers:

            X-User-Id: 100

            X-Product-Id: apac-398-472

          response_example: "Client IP: $remote_addr"
```

将配置应用到集群：

```
kubectl apply -f mocking-ic.yaml
```

❶ 配置预期的模拟响应头 `X-User-Id: 100`。

❷ 配置预期的模拟响应头 `X-Product-Id: apac-398-472`。

❸ 配置预期的模拟响应体以显示客户端 IP 地址。

发送请求到路由：

```
curl -i "http://127.0.0.1:9080/anything"
```

你应该收到类似以下的响应：

```
HTTP/1.1 200 OK

...

X-Product-Id: apac-398-472

X-User-Id: 100



Client IP: 192.168.65.1
```

### 使用 JSON Schema 生成模拟响应[​](#使用-json-schema-生成模拟响应 "使用 JSON Schema 生成模拟响应的直接链接")

以下示例演示了如何配置插件以生成遵循特定 [JSON schema](https://json-schema.org) 的模拟响应。

创建一个使用 `mocking` 插件的路由，并为预期的模拟响应定义 JSON schema：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "mocking-route",

    "uri": "/anything",

    "plugins": {

      "mocking": {

        "response_schema": {

          "type": "object",

          "properties": {

            "id": {

              "type": "string",

              "example": "abcd"

            },

            "ip": {

              "type": "string",

              "example": "192.168.0.10"

            },

            "random_str_arr": {

              "type": "array",

              "items": {

                "type": "string"

              }

            },

            "nested_obj": {

              "type": "object",

              "properties": {

                "random_str": {

                  "type": "string"

                },

                "child_nested_obj": {

                  "type": "object",

                  "properties": {

                    "random_bool": {

                      "type": "boolean",

                      "example": true

                    },

                    "random_int_arr": {

                      "type": "array",

                      "items": {

                        "type": "integer",

                        "example": 155

                      }

                    }

                  }

                }

              }

            }

          }

        }

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org": 1

      }

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    routes:

      - name: mocking-route

        uris:

          - /anything

        plugins:

          mocking:

            response_schema:

              type: object

              properties:

                id:

                  type: string

                  example: abcd

                ip:

                  type: string

                  example: "192.168.0.10"

                random_str_arr:

                  type: array

                  items:

                    type: string

                nested_obj:

                  type: object

                  properties:

                    random_str:

                      type: string

                    child_nested_obj:

                      type: object

                      properties:

                        random_bool:

                          type: boolean

                          example: true

                        random_int_arr:

                          type: array

                          items:

                            type: integer

                            example: 155

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，并确认变更仅影响本指南使用的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=mocking
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=mocking
```

* Gateway API
* APISIX CRD

mocking-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: mocking-plugin-config

spec:

  plugins:

    - name: mocking

      config:

        response_schema:

          type: object

          properties:

            id:

              type: string

              example: abcd

            ip:

              type: string

              example: "192.168.0.10"

            random_str_arr:

              type: array

              items:

                type: string

            nested_obj:

              type: object

              properties:

                random_str:

                  type: string

                child_nested_obj:

                  type: object

                  properties:

                    random_bool:

                      type: boolean

                      example: true

                    random_int_arr:

                      type: array

                      items:

                        type: integer

                        example: 155

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: mocking-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: mocking-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将配置应用到集群：

```
kubectl apply -f mocking-ic.yaml
```

mocking-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Domain

    name: httpbin.org

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: mocking-route

spec:

  ingressClassName: apisix

  http:

    - name: mocking-route

      match:

        paths:

          - /anything

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: mocking

        enable: true

        config:

          response_schema:

            type: object

            properties:

              id:

                type: string

                example: abcd

              ip:

                type: string

                example: "192.168.0.10"

              random_str_arr:

                type: array

                items:

                  type: string

              nested_obj:

                type: object

                properties:

                  random_str:

                    type: string

                  child_nested_obj:

                    type: object

                    properties:

                      random_bool:

                        type: boolean

                        example: true

                      random_int_arr:

                        type: array

                        items:

                          type: integer

                          example: 155
```

将配置应用到集群：

```
kubectl apply -f mocking-ic.yaml
```

发送请求到路由：

```
curl -i "http://127.0.0.1:9080/anything"
```

你应该看到类似以下的模拟响应，而没有来自上游服务的实际响应：

```
{

  "ip":"192.168.0.10",

  "random_str_arr":[

    "fb","lyquibkwc","r"

  ],

  "id":"abcd",

  "nested_obj":{

    "random_str":"bzbb",

    "child_nested_obj":{

      "random_bool":true,

      "random_int_arr":[155,155,155]

    }

  }

}
```
