How to create expectation on Mockserver

Stanley Meng
1 min readJul 26, 2023

I mean this mockserver: https://www.mock-server.com

A super simple sample is:

curl -X PUT "http://mockserver/mockserver/expectation"  -H 'Content-Type: application/x-www-form-urlencoded'  -d  '{ "httpRequest": { "method": "GET", "path": "/hi" }, "httpResponse": {"body": {"say": "hello world"}}}'

Test:

 $ curl  -w "%{http_code}\n"  http://mockserver/hi
{
"say" : "hello"
}200

I won’t write this blog if that’s it…

How if I want to get different responses according to different path parameter? (dynamic response?) For instance , http://mockserver/node/1 and http://mockserver/node/2 return different responses.

Write a json file with the following mock expectation, say, /tmp/expect.json

[{
"httpRequest": {
"method": "GET",
"path": "/ifnode/{nodeId}",
"pathParameters": {
"nodeId": ["[0-9\\-]+"]
}
},
"httpResponseTemplate": {
"template": "#if($request.path == '/ifnode/1'){ \"statusCode\": 200, \"body\": \"$!request.path\n\" } #else {\"statusCode\": 406, \"body\": \"$!request.path\n\"} #end",
"templateType": "VELOCITY"
}
}]

Run command:

curl -X PUT "http://mockserver/mockserver/expectation"  -H 'Content-Type: application/x-www-form-urlencoded'  -d  " `cat /tmp/expect.json`  "

Test:

$ curl  -w "%{http_code}\n"  http://mockserver/ifnode/1
/ifnode/1
200
$ curl -w "%{http_code}\n" http://mockserver/ifnode/2
/ifnode/2
406

How if I want to get different responses according to different query parameters? For instance, http://mockserver/knode?nodeId=1 and http://mockserver/knode?nodeId=2 return different response.

Write a json file with the expectation:

[{
"httpRequest": {
"method": "GET",
"path": "/knode",
"queryStringParameters": {
"?nodeId": ["[0-9\\-]+"]
}
},
"httpResponseTemplate": {
"template": "#if($request.queryStringParameters.nodeId[0] == '1'){ \"statusCode\": 200, \"body\": \"$!request.queryStringParameters.nodeId\n\" } #else {\"statusCode\": 406, \"body\": \"$!request.queryStringParameters.nodeId\n\"} #end",
"templateType": "VELOCITY"
}
}]

Run the command:

curl -X PUT "http://mockserver/mockserver/expectation"  -H 'Content-Type: application/x-www-form-urlencoded'  -d  " `cat /tmp/expect.json`  "

Test:

$ curl  -w "%{http_code}\n"  http://mockserver/knode?nodeId=1
[1]
200
$ curl -w "%{http_code}\n" http://mockserver/knode?nodeId=3
[3]
406

--

--