第二节 wireMock用json模拟HTTP请求

本文介绍了wireMock如何模拟各种HTTP请求,包括GET、POST、DELETE接口,404错误处理,PUT请求以及Query参数匹配,并提及了故障模拟功能。欲了解更多高级用法,可参考后续章节关于URL匹配的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,HTTP请求

1)GET接口

{
    "request": {
        "method": "GET",
        "url": "/api/mytest"
    },
    "response": {
        "status": 200,
        "body": "More content\n"
    }
}

2)POST接口

{
    "request": {
        "method": "POST",
        "url": "/api/products",


          "bodyPatterns": [
                 {"equalToJson" : "{ \"name\": \"new product\", \"creator\": \"tester\", \"createTime\": \"2015-09-07\" }",


 "jsonCompareMode": "LENIENT"}
         ]
    },
    "response": {
        "status": 200,
        "body": "Add successfully.",
         "headers":{
                   "x-token":"xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
         }
    }

}

3)DELETE接口

{
    "request": {
        "method": "DELETE",
        "url": "/api/products/delete" 
    },
    "response": {
        "status": 204,      
        "headers":{
                  "x-token":" xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        }
    }
}

4)404错误

{
"priority": 10,
    "request": {
        "url": "/unknown.html",
        "method": "GET"
    },
    "response": {
        "status": 404,
        "headers": {
            "Content-Type": "text/html; charset=utf-8"
        }
    }
}

5)PUT请求:

{
    "request": {
        "method": "PUT",
        "url": "/api/products/1",
          "bodyPatterns": [
            {"equalToJson" : "{ \"id\": 1, \"name\": \"new product\", \"creator\": \"tester\", \"createTime\": \"2015-09-07\" }", "jsonCompareMode": "LENIENT"}
         ]
    },
    "response": {
        "status": 200,
        "body": "Update successfully.",
         "headers":{
                  "x-token":" xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
         }
    }
}

5)Query参数匹配:

{
    "request": {
        "method": "GET",
        "urlPath": "/api/products",
        "queryParameters": {
            "search": {
                "contains": "chin"
            }
        }
    },
    "response": {
            "status": 200,
             "headers":{ "Content-Type": "application/json"},
              "body": "{ \"id\": 7, \"name\": \"shan zai\", \"from\":\"China\" },{ \"id\": 7, \"name\": \"shan zai\", \"from\":\"China(RPC)\" }"
    }
}

6)故障模拟

{
    "request": {
        "method": "GET",
        "url": "/fault"
    },
    "response": {
        "fault": "MALFORMED_RESPONSE_CHUNK"
    }
}

拓展用法请看下一节《第三节 URL的匹配方法》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值