The following code examples show how to create different forward actions.
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
forward()
.withHost("mock-server.com")
.withPort(80)
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/some/path"
},
"httpForward": {
"host": "mock-server.com",
"port": 80,
"scheme": "HTTP"
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpForward": {
"host": "mock-server.com",
"port": 80,
"scheme": "HTTP"
}
}'
See REST API for full JSON specification
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
forward()
.withHost("mock-server.com")
.withPort(443)
.withScheme(HttpForward.Scheme.HTTPS)
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/some/path"
},
"httpForward": {
"host": "mock-server.com",
"port": 443,
"scheme": "HTTPS"
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpForward": {
"host": "mock-server.com",
"port": 443,
"scheme": "HTTPS"
}
}'
See REST API for full JSON specification
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
forwardOverriddenRequest(
request()
.withPath("/some/other/path")
.withHeader("Host", "target.host.com")
)
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"httpRequest": {
"path": "/some/other/path",
"headers": {
"Host": ["target.host.com"]
}
}
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"httpRequest": {
"path": "/some/other/path",
"headers": {
"Host": ["target.host.com"]
}
}
}
}'
See REST API for full JSON specification
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
forwardOverriddenRequest(
request()
.withPath("/some/other/path")
.withHeader("Host", "target.host.com"),
response()
.withBody("some_overridden_body")
)
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"httpRequest": {
"path": "/some/other/path",
"headers": {
"Host": ["target.host.com"]
}
},
"httpResponse": {
"body": "some_overridden_body"
}
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"httpRequest": {
"path": "/some/other/path",
"headers": {
"Host": ["target.host.com"]
}
},
"httpResponse": {
"body": "some_overridden_body"
}
}
}'
See REST API for full JSON specification
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
forwardOverriddenRequest(
request()
// this replaces the entire set of headers
.withHeader("Host", "target.host.com")
.withBody("some_overridden_body"),
requestModifier()
.withPath("^/(.+)/(.+)$", "/prefix/$1/infix/$2/postfix")
.withQueryStringParameters(
queryParametersModifier()
.add(
param("parameterToAddOne", "addedValue"),
param("parameterToAddTwo", "addedValue")
)
.replace(
param("overrideParameterToReplace", "replacedValue"),
param("requestParameterToReplace", "replacedValue"),
param("extraParameterToReplace", "shouldBeIgnore")
)
.remove(
"overrideParameterToRemove",
"requestParameterToRemove"
)
)
// this modifies the set of headers
.withHeaders(
headersModifier()
.add(
header("headerToAddOne", "addedValue"),
header("headerToAddTwo", "addedValue")
)
.replace(
header("overrideHeaderToReplace", "replacedValue"),
header("requestHeaderToReplace", "replacedValue"),
header("extraHeaderToReplace", "shouldBeIgnore")
)
.remove(
"overrideHeaderToRemove",
"requestHeaderToRemove"
)
)
.withCookies(
cookiesModifier()
.add(
cookie("cookieToAddOne", "addedValue"),
cookie("cookieToAddTwo", "addedValue")
)
.replace(
cookie("overrideCookieToReplace", "replacedValue"),
cookie("requestCookieToReplace", "replacedValue"),
cookie("extraCookieToReplace", "shouldBeIgnore")
)
.remove(
"overrideCookieToRemove",
"requestCookieToRemove"
)
)
)
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"requestOverride": {
"headers": {
"Host": [
"target.host.com"
]
},
"body": "some_overridden_body"
},
"requestModifier": {
"cookies": {
"add": {
"cookieToAddOne": "addedValue",
"cookieToAddTwo": "addedValue"
},
"remove": [
"overrideCookieToRemove",
"requestCookieToRemove"
],
"replace": {
"overrideCookieToReplace": "replacedValue",
"requestCookieToReplace": "replacedValue",
"extraCookieToReplace": "shouldBeIgnore"
}
},
"headers": {
"add": {
"headerToAddTwo": [
"addedValue"
],
"headerToAddOne": [
"addedValue"
]
},
"remove": [
"overrideHeaderToRemove",
"requestHeaderToRemove"
],
"replace": {
"requestHeaderToReplace": [
"replacedValue"
],
"overrideHeaderToReplace": [
"replacedValue"
],
"extraHeaderToReplace": [
"shouldBeIgnore"
]
}
},
"path": {
"regex": "^/(.+)/(.+)$",
"substitution": "/prefix/$1/infix/$2/postfix"
},
"queryStringParameters": {
"add": {
"parameterToAddTwo": [
"addedValue"
],
"parameterToAddOne": [
"addedValue"
]
},
"remove": [
"overrideParameterToRemove",
"requestParameterToRemove"
],
"replace": {
"requestParameterToReplace": [
"replacedValue"
],
"overrideParameterToReplace": [
"replacedValue"
],
"extraParameterToReplace": [
"shouldBeIgnore"
]
}
}
}
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"requestOverride": {
"headers": {
"Host": [
"target.host.com"
]
},
"body": "some_overridden_body"
},
"requestModifier": {
"cookies": {
"add": {
"cookieToAddOne": "addedValue",
"cookieToAddTwo": "addedValue"
},
"remove": [
"overrideCookieToRemove",
"requestCookieToRemove"
],
"replace": {
"overrideCookieToReplace": "replacedValue",
"requestCookieToReplace": "replacedValue",
"extraCookieToReplace": "shouldBeIgnore"
}
},
"headers": {
"add": {
"headerToAddTwo": [
"addedValue"
],
"headerToAddOne": [
"addedValue"
]
},
"remove": [
"overrideHeaderToRemove",
"requestHeaderToRemove"
],
"replace": {
"requestHeaderToReplace": [
"replacedValue"
],
"overrideHeaderToReplace": [
"replacedValue"
],
"extraHeaderToReplace": [
"shouldBeIgnore"
]
}
},
"path": {
"regex": "^/(.+)/(.+)$",
"substitution": "/prefix/$1/infix/$2/postfix"
},
"queryStringParameters": {
"add": {
"parameterToAddTwo": [
"addedValue"
],
"parameterToAddOne": [
"addedValue"
]
},
"remove": [
"overrideParameterToRemove",
"requestParameterToRemove"
],
"replace": {
"requestParameterToReplace": [
"replacedValue"
],
"overrideParameterToReplace": [
"replacedValue"
],
"extraParameterToReplace": [
"shouldBeIgnore"
]
}
}
}
}
}'
See REST API for full JSON specification
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
forwardOverriddenRequest()
.withRequestOverride(
request()
// this replaces the entire set of headers
.withHeader("Host", "target.host.com")
.withBody("some_overridden_body")
)
.withRequestModifier(
requestModifier()
.withPath("^/(.+)/(.+)$", "/prefix/$1/infix/$2/postfix")
.withQueryStringParameters(
queryParametersModifier()
.add(
param("parameterToAddOne", "addedValue"),
param("parameterToAddTwo", "addedValue")
)
.replace(
param("overrideParameterToReplace", "replacedValue"),
param("requestParameterToReplace", "replacedValue"),
param("extraParameterToReplace", "shouldBeIgnore")
)
.remove(
"overrideParameterToRemove",
"requestParameterToRemove"
)
)
// this modifies the set of headers
.withHeaders(
headersModifier()
.add(
header("headerToAddOne", "addedValue"),
header("headerToAddTwo", "addedValue")
)
.replace(
header("overrideHeaderToReplace", "replacedValue"),
header("requestHeaderToReplace", "replacedValue"),
header("extraHeaderToReplace", "shouldBeIgnore")
)
.remove(
"overrideHeaderToRemove",
"requestHeaderToRemove"
)
)
.withCookies(
cookiesModifier()
.add(
cookie("cookieToAddOne", "addedValue"),
cookie("cookieToAddTwo", "addedValue")
)
.replace(
cookie("overrideCookieToReplace", "replacedValue"),
cookie("requestCookieToReplace", "replacedValue"),
cookie("extraCookieToReplace", "shouldBeIgnore")
)
.remove(
"overrideCookieToRemove",
"requestCookieToRemove"
)
)
)
.withResponseOverride(
response()
.withBody("some_overridden_body")
)
.withResponseModifier(
responseModifier()
.withHeaders(
headersModifier()
.add(
header("headerToAddOne", "addedValue"),
header("headerToAddTwo", "addedValue")
)
.replace(
header("overrideHeaderToReplace", "replacedValue"),
header("requestHeaderToReplace", "replacedValue"),
header("extraHeaderToReplace", "shouldBeIgnore")
)
.remove(
"overrideHeaderToRemove",
"requestHeaderToRemove"
)
)
.withCookies(
cookiesModifier()
.add(
cookie("cookieToAddOne", "addedValue"),
cookie("cookieToAddTwo", "addedValue")
)
.replace(
cookie("overrideCookieToReplace", "replacedValue"),
cookie("requestCookieToReplace", "replacedValue"),
cookie("extraCookieToReplace", "shouldBeIgnore")
)
.remove(
"overrideCookieToRemove",
"requestCookieToRemove"
)
)
)
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"requestOverride": {
"headers": {
"Host": [
"target.host.com"
]
},
"body": "some_overridden_body"
},
"requestModifier": {
"cookies": {
"add": {
"cookieToAddOne": "addedValue",
"cookieToAddTwo": "addedValue"
},
"remove": [
"overrideCookieToRemove",
"requestCookieToRemove"
],
"replace": {
"overrideCookieToReplace": "replacedValue",
"requestCookieToReplace": "replacedValue",
"extraCookieToReplace": "shouldBeIgnore"
}
},
"headers": {
"add": {
"headerToAddTwo": [
"addedValue"
],
"headerToAddOne": [
"addedValue"
]
},
"remove": [
"overrideHeaderToRemove",
"requestHeaderToRemove"
],
"replace": {
"requestHeaderToReplace": [
"replacedValue"
],
"overrideHeaderToReplace": [
"replacedValue"
],
"extraHeaderToReplace": [
"shouldBeIgnore"
]
}
},
"path": {
"regex": "^/(.+)/(.+)$",
"substitution": "/prefix/$1/infix/$2/postfix"
},
"queryStringParameters": {
"add": {
"parameterToAddTwo": [
"addedValue"
],
"parameterToAddOne": [
"addedValue"
]
},
"remove": [
"overrideParameterToRemove",
"requestParameterToRemove"
],
"replace": {
"requestParameterToReplace": [
"replacedValue"
],
"overrideParameterToReplace": [
"replacedValue"
],
"extraParameterToReplace": [
"shouldBeIgnore"
]
}
}
},
"responseOverride": {
"body": "some_overridden_body"
},
"responseModifier": {
"cookies": {
"add": {
"cookieToAddOne": "addedValue",
"cookieToAddTwo": "addedValue"
},
"remove": [
"overrideCookieToRemove",
"requestCookieToRemove"
],
"replace": {
"overrideCookieToReplace": "replacedValue",
"requestCookieToReplace": "replacedValue",
"extraCookieToReplace": "shouldBeIgnore"
}
},
"headers": {
"add": {
"headerToAddTwo": [
"addedValue"
],
"headerToAddOne": [
"addedValue"
]
},
"remove": [
"overrideHeaderToRemove",
"requestHeaderToRemove"
],
"replace": {
"requestHeaderToReplace": [
"replacedValue"
],
"overrideHeaderToReplace": [
"replacedValue"
],
"extraHeaderToReplace": [
"shouldBeIgnore"
]
}
}
}
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"requestOverride": {
"headers": {
"Host": [
"target.host.com"
]
},
"body": "some_overridden_body"
},
"requestModifier": {
"cookies": {
"add": {
"cookieToAddOne": "addedValue",
"cookieToAddTwo": "addedValue"
},
"remove": [
"overrideCookieToRemove",
"requestCookieToRemove"
],
"replace": {
"overrideCookieToReplace": "replacedValue",
"requestCookieToReplace": "replacedValue",
"extraCookieToReplace": "shouldBeIgnore"
}
},
"headers": {
"add": {
"headerToAddTwo": [
"addedValue"
],
"headerToAddOne": [
"addedValue"
]
},
"remove": [
"overrideHeaderToRemove",
"requestHeaderToRemove"
],
"replace": {
"requestHeaderToReplace": [
"replacedValue"
],
"overrideHeaderToReplace": [
"replacedValue"
],
"extraHeaderToReplace": [
"shouldBeIgnore"
]
}
},
"path": {
"regex": "^/(.+)/(.+)$",
"substitution": "/prefix/$1/infix/$2/postfix"
},
"queryStringParameters": {
"add": {
"parameterToAddTwo": [
"addedValue"
],
"parameterToAddOne": [
"addedValue"
]
},
"remove": [
"overrideParameterToRemove",
"requestParameterToRemove"
],
"replace": {
"requestParameterToReplace": [
"replacedValue"
],
"overrideParameterToReplace": [
"replacedValue"
],
"extraParameterToReplace": [
"shouldBeIgnore"
]
}
}
},
"responseOverride": {
"body": "some_overridden_body"
},
"responseModifier": {
"cookies": {
"add": {
"cookieToAddOne": "addedValue",
"cookieToAddTwo": "addedValue"
},
"remove": [
"overrideCookieToRemove",
"requestCookieToRemove"
],
"replace": {
"overrideCookieToReplace": "replacedValue",
"requestCookieToReplace": "replacedValue",
"extraCookieToReplace": "shouldBeIgnore"
}
},
"headers": {
"add": {
"headerToAddTwo": [
"addedValue"
],
"headerToAddOne": [
"addedValue"
]
},
"remove": [
"overrideHeaderToRemove",
"requestHeaderToRemove"
],
"replace": {
"requestHeaderToReplace": [
"replacedValue"
],
"overrideHeaderToReplace": [
"replacedValue"
],
"extraHeaderToReplace": [
"shouldBeIgnore"
]
}
}
}
}
}'
See REST API for full JSON specification
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
forwardOverriddenRequest(
request()
.withPath("/some/other/path")
.withHeader("Host", "any.host.com")
.withSocketAddress("target.host.com", 1234, SocketAddress.Scheme.HTTPS)
)
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"httpRequest": {
"path": "/some/other/path",
"headers": {
"Host": ["any.host.com"]
},
"socketAddress": {
"host": "target.host.com",
"port": 1234,
"scheme": "HTTPS"
}
}
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"httpRequest": {
"path": "/some/other/path",
"headers": {
"Host": ["any.host.com"]
},
"socketAddress": {
"host": "target.host.com",
"port": 1234,
"scheme": "HTTPS"
}
}
}
}'
See REST API for full JSON specification
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
forwardOverriddenRequest(
request()
.withHeader("Host", "target.host.com")
.withBody("some_overridden_body")
).withDelay(SECONDS, 10)
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"httpRequest": {
"path": "/some/other/path",
"body": "some_overridden_body",
"headers": {
"Host": ["target.host.com"]
}
},
"delay": {
"timeUnit": "SECONDS",
"value": 10
}
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"httpRequest": {
"path": "/some/other/path",
"body": "some_overridden_body",
"headers": {
"Host": ["target.host.com"]
}
},
"delay": {
"timeUnit": "SECONDS",
"value": 10
}
}
}'
See REST API for full JSON specification
Forward actions support the same distribution-based delays as response actions, allowing realistic latency simulation when proxying requests.
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
forwardOverriddenRequest(
request()
.withHeader("Host", "target.host.com")
.withBody("some_overridden_body")
).withDelay(Delay.logNormal(TimeUnit.MILLISECONDS, 200, 800))
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"httpRequest": {
"path": "/some/other/path",
"body": "some_overridden_body",
"headers": {
"Host": ["target.host.com"]
}
},
"delay": {
"timeUnit": "MILLISECONDS",
"distribution": {
"type": "LOG_NORMAL",
"median": 200,
"p99": 800
}
}
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"httpRequest": {
"path": "/some/other/path",
"body": "some_overridden_body",
"headers": {
"Host": ["target.host.com"]
}
},
"delay": {
"timeUnit": "MILLISECONDS",
"distribution": {
"type": "LOG_NORMAL",
"median": 200,
"p99": 800
}
}
}
}'
See REST API for full JSON specification
// request.queryStringParameters['userId'] returns an array of values because headers and queryStringParameters have multiple values
String template = "return {\n" +
" 'path' : \"/somePath\",\n" +
" 'queryStringParameters' : {\n" +
" 'userId' : request.queryStringParameters && request.queryStringParameters['userId']\n" +
" },\n" +
" 'headers' : {\n" +
" 'Host' : [ \"localhost:1081\" ]\n" +
" },\n" +
" 'body': JSON.stringify({'name': 'value'})\n" +
"};";
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
template(
HttpTemplate.TemplateType.JAVASCRIPT,
template
)
);
var mockServerClient = require('mockserver-client').mockServerClient;
// request.queryStringParameters['userId'] returns an array of values because headers and queryStringParameters have multiple values
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/some/path"
},
"httpForwardTemplate": {
"template": "return {\n" +
" 'path' : \"/somePath\",\n" +
" 'queryStringParameters' : {\n" +
" 'userId' : request.queryStringParameters && request.queryStringParameters['userId']\n" +
" },\n" +
" 'headers' : {\n" +
" 'Host' : [ \"localhost:1081\" ]\n" +
" },\n" +
" 'body': JSON.stringify({'name': 'value'})\n" +
"};",
"templateType": "JAVASCRIPT"
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpForwardTemplate": {
"template": "return {\n" +
" 'path' : \"/somePath\",\n" +
" 'queryStringParameters' : {\n" +
" 'userId' : request.queryStringParameters && request.queryStringParameters['userId']\n" +
" },\n" +
" 'headers' : {\n" +
" 'Host' : [ \"localhost:1081\" ]\n" +
" },\n" +
" 'body': JSON.stringify({'name': 'value'})\n" +
"};",
"templateType": "JAVASCRIPT"
}
}'
See REST API for full JSON specification
String template = "return {" + System.getProperty("line.separator") +
" 'path' : request.path.substring(request.path.indexOf('/somePrefix')+'/somePrefix'.length,request.path.length)," + System.getProperty("line.separator") +
" 'headers' : {" + System.getProperty("line.separator") +
" 'Host' : [ \"localhost:1081\" ]" + System.getProperty("line.separator") +
" }," + System.getProperty("line.separator") +
"};";
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/somePrefix*")
)
.forward(
template(
HttpTemplate.TemplateType.JAVASCRIPT,
template
)
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/somePrefix*"
},
"httpForwardTemplate": {
"template": "return {\n" +
" 'path' : request.path.substring(request.path.indexOf('/somePrefix')+'/somePrefix'.length,request.path.length),\n" +
" 'headers' : {\n" +
" 'Host' : [ \"localhost:1081\" ]\n" +
" }
"};",
"templateType": "JAVASCRIPT"
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/somePrefix*"
},
"httpForwardTemplate": {
"template": "return {\n" +
" 'path' : request.path.substring(request.path.indexOf('/somePrefix')+'/somePrefix'.length,request.path.length),\n" +
" 'headers' : {\n" +
" 'Host' : [ \"localhost:1081\" ]\n" +
" }\n" +
"};",
"templateType": "JAVASCRIPT"
}
}'
See REST API for full JSON specification
// request.cookies['SessionId'] returns a single value because cookies only contain a single value
String template = "return {\n" +
" 'path' : \"/somePath\",\n" +
" 'cookies' : {\n" +
" 'SessionId' : request.cookies && request.cookies['SessionId']\n" +
" },\n" +
" 'headers' : {\n" +
" 'Host' : [ \"localhost:1081\" ]\n" +
" },\n" +
" 'keepAlive' : true,\n" +
" 'secure' : true,\n" +
" 'body' : \"some_body\"\n" +
"};";
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
template(HttpTemplate.TemplateType.JAVASCRIPT)
.withTemplate(template)
.withDelay(TimeUnit.SECONDS, 20)
);
var mockServerClient = require('mockserver-client').mockServerClient;
// request.cookies['SessionId'] returns a single value because cookies only contain a single value
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/some/path"
},
"httpForwardTemplate": {
"template": "return {\n" +
" 'path' : \"/somePath\",\n" +
" 'cookies' : {\n" +
" 'SessionId' : request.cookies && request.cookies['SessionId']\n" +
" },\n" +
" 'headers' : {\n" +
" 'Host' : [ \"localhost:1081\" ]\n" +
" },\n" +
" 'keepAlive' : true,\n" +
" 'secure' : true,\n" +
" 'body' : \"some_body\"\n" +
"};",
"templateType": "JAVASCRIPT",
"delay": {"timeUnit": "SECONDS", "value": 20}
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpForwardTemplate": {
"template": "return {\n" +
" 'path' : \"/somePath\",\n" +
" 'cookies' : {\n" +
" 'SessionId' : request.cookies && request.cookies['SessionId']\n" +
" },\n" +
" 'headers' : {\n" +
" 'Host' : [ \"localhost:1081\" ]\n" +
" },\n" +
" 'keepAlive' : true,\n" +
" 'secure' : true,\n" +
" 'body' : \"some_body\"\n" +
"};",
"templateType": "JAVASCRIPT",
"delay": {"timeUnit": "SECONDS", "value": 20}
}
}'
See REST API for full JSON specification
// $!request.queryStringParameters['userId'] returns an array of values because headers and queryStringParameters have multiple values
String template = "{\n" +
" 'path' : \"/somePath\",\n" +
" 'queryStringParameters' : {\n" +
" 'userId' : [ \"$!request.queryStringParameters['userId'][0]\" ]\n" +
" },\n" +
" 'cookies' : {\n" +
" 'SessionId' : \"$!request.cookies['SessionId']\"\n" +
" },\n" +
" 'headers' : {\n" +
" 'Host' : [ \"localhost:1081\" ]\n" +
" },\n" +
" 'body': \"{'name': 'value'}\"\n" +
"}";
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
template(
HttpTemplate.TemplateType.VELOCITY,
template
)
);
var mockServerClient = require('mockserver-client').mockServerClient;
// $!request.queryStringParameters['userId'] returns an array of values because headers and queryStringParameters have multiple values
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/some/path"
},
"httpForwardTemplate": {
"template": "{\n" +
" 'path' : \"/somePath\",\n" +
" 'queryStringParameters' : {\n" +
" 'userId' : [ \"$!request.queryStringParameters['userId'][0]\" ]\n" +
" },\n" +
" 'cookies' : {\n" +
" 'SessionId' : \"$!request.cookies['SessionId']\"\n" +
" },\n" +
" 'headers' : {\n" +
" 'Host' : [ \"localhost:1081\" ]\n" +
" },\n" +
" 'body': \"{'name': 'value'}\"\n" +
"}",
"templateType": "VELOCITY"
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpForwardTemplate": {
"template": "{\n" +
" 'path' : \"/somePath\",\n" +
" 'queryStringParameters' : {\n" +
" 'userId' : [ \"$!request.queryStringParameters['userId'][0]\" ]\n" +
" },\n" +
" 'cookies' : {\n" +
" 'SessionId' : \"$!request.cookies['SessionId']\"\n" +
" },\n" +
" 'headers' : {\n" +
" 'Host' : [ \"localhost:1081\" ]\n" +
" },\n" +
" 'body': \"{'name': 'value'}\"\n" +
"}",
"templateType": "VELOCITY"
}
}'
See REST API for full JSON specification
A response template allows you to transform the response returned from the upstream server using a template that has access to both the original request and the upstream response. This is useful when you need to dynamically modify responses based on request context — for example, injecting request headers into the response body or conditionally changing the status code.
The template receives two objects: request (the original request) and response (the upstream response). The template must return a valid HTTP response JSON object.
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpOverrideForwardedRequest": {
"requestOverride": {
"headers": {
"Host": ["target.host.com"]
}
},
"responseTemplate": {
"templateType": "JAVASCRIPT",
"template": "return { 'statusCode': response.statusCode, 'headers': response.headers, 'body': JSON.stringify({ 'originalBody': response.body, 'requestPath': request.path }) };"
}
}
}'
See REST API for full JSON specification
When using a templated forward (JavaScript, Velocity, or Mustache), you can also specify a responseOverride and/or responseModifier to statically modify the response returned from the upstream server — without needing a separate response template.
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpForwardTemplate": {
"templateType": "JAVASCRIPT",
"template": "return { 'path': '/target' + request.path, 'headers': { 'Host': ['target.host.com'] } };",
"responseOverride": {
"headers": {
"x-proxy": ["mockserver"]
}
}
}
}'
See REST API for full JSON specification
public class CallbackActionExamples {
public void forwardClassCallback() {
new ClientAndServer(1080)
.when(
request()
.withPath("/some.*")
)
.forward(
callback()
.withCallbackClass(TestExpectationForwardCallback.class)
);
}
public static class TestExpectationForwardCallback implements ExpectationForwardCallback {
@Override
public HttpRequest handle(HttpRequest httpRequest) {
return request()
.withPath(httpRequest.getPath())
.withMethod("POST")
.withHeaders(
header("x-callback", "test_callback_header"),
header("Content-Length", "a_callback_request".getBytes(UTF_8).length),
header("Connection", "keep-alive")
)
.withBody("a_callback_request");
}
}
}
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"path": "/some.*"
},
"httpForwardClassCallback": {
"callbackClass": "org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationForwardCallback"
}
}).then(
function () {
console.log("expectation created");
},
function (error) {
console.log(error);
}
);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest" : {
"path" : "/some.*"
},
"httpForwardClassCallback" : {
"callbackClass" : "org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationForwardCallback"
}
}'
To use a class callback MockServer must be able to load the class from the classpath.
The callback class must:
If MockServer is started using the JUnit 4 @Rule, the JUnit 5 Test Extension, ClientAndServer or directly using org.mockserver.netty.MockServer then any class present in the main or test classpaths will be visible to MockServer.
If MockServer is started using the maven plugin only the non-forked goals (such as runAndWait and start) will be able to load classes from the main and test classpaths. It is possible to use classes from a separate maven dependency, however, this dependency must be specified in the plugin configuration dependencies section. Any dependency added to the plugin configuration dependencies section will then be visible to MockServer run using both forked and non-forked goals.
The following configuration shows how to use classes from a separate maven dependency in callback actions.
<plugin>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-maven-plugin</artifactId>
<version>{{ site.mockserver_version }}</version>
<configuration>
<serverPort>1080</serverPort>
<logLevel>DEBUG</logLevel>
<pipeLogToConsole>true</pipeLogToConsole>
</configuration>
<executions>
<execution>
<id>pre-integration-test</id>
<phase>pre-integration-test</phase>
<goals>
<goal>runForked</goal>
</goals>
</execution>
<execution>
<id>post-integration-test</id>
<phase>post-integration-test</phase>
<goals>
<goal>stopForked</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.my-domain</groupId>
<artifactId>my-callback-dependency</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</plugin>
If MockServer is started using the command line then the callback classes must be added to the JVM using the classpath command line switch (cp or classpath). The classpath switch is ignored by the JVM if the jar switch is used. So to run the MockServer from the command line directly (with mockserver-netty-{{ site.mockserver_version }}-no-dependencies.jar) you must specify the org.mockserver.cli.Main main class specifically and not use the jar switch as follows.
java -Dfile.encoding=UTF-8 -cp mockserver-netty-{{ site.mockserver_version }}-no-dependencies.jar:my-callback-dependency.jar org.mockserver.cli.Main -serverPort 1080
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
new ExpectationForwardCallback() {
@Override
public HttpRequest handle(HttpRequest httpRequest) {
return request()
.withPath(httpRequest.getPath())
.withMethod("POST")
.withHeaders(
header("x-callback", "test_callback_header"),
header("Content-Length", "a_callback_request".getBytes(UTF_8).length),
header("Connection", "keep-alive")
)
.withBody("a_callback_request");
}
}
);
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
httpRequest -> request()
.withPath(httpRequest.getPath())
.withMethod("POST")
.withHeaders(
header("x-callback", "test_callback_header"),
header("Content-Length", "a_callback_request".getBytes(UTF_8).length),
header("Connection", "keep-alive")
)
.withBody("a_callback_request")
);
When using org.mockserver.client.MockServerClient each method / closure callback has a separate web socket client. To ensure the number of total threads does not grow too large for large numbers of method / closure callback expectations the default event loop thread pool for the web socket client is kept fairly low. However, if an extremely large load is matched against a single method / closure callback expectation the event loop thread pool may not be large enough for its web socket client.
The number of threads for the event loop thread pool for each web socket client (i.e. for each expectation with a method / closure callback) can be configured and is described in the configuration section.
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
new ExpectationForwardCallback() {
@Override
public HttpRequest handle(HttpRequest httpRequest) throws Exception {
return request()
.withPath(httpRequest.getPath())
.withMethod("POST")
.withHeaders(
header("x-callback", "test_callback_header"),
header("Content-Length", "a_callback_request".getBytes(UTF_8).length),
header("Connection", "keep-alive")
)
.withBody("a_callback_request");
}
},
new ExpectationForwardAndResponseCallback() {
@Override
public HttpResponse handle(HttpRequest httpRequest, HttpResponse httpResponse) throws Exception {
return httpResponse
.withHeader("x-response-test", "x-response-test")
.removeHeader(CONTENT_LENGTH.toString())
.withBody("some_overridden_response_body");
}
}
);
new MockServerClient("localhost", 1080)
.when(
request()
.withPath("/some/path")
)
.forward(
httpRequest ->
request()
.withPath(httpRequest.getPath())
.withMethod("POST")
.withHeaders(
header("x-callback", "test_callback_header"),
header("Content-Length", "a_callback_request".getBytes(UTF_8).length),
header("Connection", "keep-alive")
)
.withBody("a_callback_request"),
(httpRequest, httpResponse) ->
httpResponse
.withHeader("x-response-test", "x-response-test")
.removeHeader(CONTENT_LENGTH.toString())
.withBody("some_overridden_response_body")
);
When using org.mockserver.client.MockServerClient each method / closure callback has a separate web socket client. To ensure the number of total threads does not grow too large for large numbers of method / closure callback expectations the default event loop thread pool for the web socket client is kept fairly low. However, if an extremely large load is matched against a single method / closure callback expectation the event loop thread pool may not be large enough for its web socket client.
The number of threads for the event loop thread pool for each web socket client (i.e. for each expectation with a method / closure callback) can be configured and is described in the configuration section.