Response Actions
Response actions contain:
- status code i.e. 200, 302, 404, etc
- body - a UTF-8 encoded sequence of bytes containing any content
- headers - each with a name and one or more values
- cookies - each with a name and with one or more values, more complex cookies can be modelled by using the a Set-Cookie header
Responses can be further controlled using:
- a delay before the response is sent
- the number of times the response is sent (including unlimited)
- a time to live the response will be continued to be returned (including unlimited)
Java
When mocking a response in Java use the org.mockserver.model.HttpResponse class which specifies the details of each HTTP response with a fluent API, for example:
HttpResponse httpResponse =
response()
.withStatusCode(401)
.withHeaders(
new Header("Content-Type", "application/json; charset=utf-8"),
new Header("Cache-Control", "public, max-age=86400")
)
.withBody("{ message: 'incorrect username and password combination' }")
.withDelay(new Delay(TimeUnit.SECONDS, 1))
.withConnectionOptions(
new ConnectionOptions()
.withKeepAliveOverride(true)
.withCloseSocket(true)
);
To control whether the socket is closed after the response has been sent or headers such as "Connection" or "Content-Length" the org.mockserver.model.ConnectionOptions class can be used.
For example:
HttpResponse httpResponse =
response()
.withStatusCode(401)
.withHeaders(
new Header("Content-Type", "application/json; charset=utf-8"),
new Header("Cache-Control", "public, max-age=86400")
)
.withBody("{ message: 'incorrect username and password combination' }")
.withDelay(new Delay(TimeUnit.SECONDS, 1))
.withConnectionOptions(
new ConnectionOptions()
.withKeepAliveOverride(true)
.withCloseSocket(true)
);
JavaScript
To mock a response in javascript use JSON to specify the details with the following format:
"httpResponse": {
"statusCode": 200,
"body": "",
"cookies": [],
"headers": [],
"delay": {
"timeUnit": "MICROSECONDS",
"value": 0
}
}
Each cookie or header array entry has the following syntax:
{
"name": "someName",
"values": ["someValueOne", "someValueTwo", ...]
}
The "timeUnit" value in "delay" can be:
"NANOSECONDS"
"MICROSECONDS"
"MILLISECONDS"
"SECONDS"
"MINUTES"
"HOURS"
"DAYS"
The same example as above would be:
"httpResponse": {
"statusCode": 401,
"headers": [
{
"name": "Content-Type",
"values": ["application/json; charset=utf-8"]
},
{
"name": "Cache-Control",
"values": ["public, max-age=86400"]
}
],
"body": JSON.stringify({ message: "incorrect username and password combination" }),
"delay": {
"timeUnit": "SECONDS",
"value": 1
}
}