Class MockServerClient
- All Implemented Interfaces:
Closeable,AutoCloseable,Stoppable
- Direct Known Subclasses:
ClientAndServer
- Author:
- jamesdbloom
-
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionMockServerClient(String host, int port) Start the client communicating to a MockServer at the specified host and port for example:MockServerClient(String host, int port, String contextPath) Start the client communicating to a MockServer at the specified host and port and contextPath for example:MockServerClient(ClientConfiguration configuration, String host, int port) Start the client communicating to a MockServer at the specified host and port for example:MockServerClient(ClientConfiguration configuration, String host, int port, String contextPath) Start the client communicating to a MockServer at the specified host and port and contextPath for example:MockServerClient(ClientConfiguration configuration, CompletableFuture<Integer> portFuture) Start the client communicating to a MockServer on localhost at the port specified with the FutureMockServerClient(Configuration configuration, String host, int port) Start the client communicating to a MockServer at the specified host and port for example:MockServerClient(Configuration configuration, String host, int port, String contextPath) Start the client communicating to a MockServer at the specified host and port and contextPath for example:MockServerClient(Configuration configuration, CompletableFuture<Integer> portFuture) Start the client communicating to a MockServer on localhost at the port specified with the Future -
Method Summary
Modifier and TypeMethodDescriptionadvanceClock(Duration duration) Advance the MockServer clock by the specified duration.Retrieve the current AsyncAPI mocking status including loaded spec info, active channels, and recorded messages.Bind new ports to listen onClear all expectations and logs that match the expectation idClear expectations, logs or both that match the expectation idclear(ExpectationId expectationId) Clear all expectations and logs that match the expectation idclear(ExpectationId expectationId, ClearType type) Clear expectations, logs or both that match the expectation idclear(RequestDefinition requestDefinition) Clear all expectations and logs that match the request matcherclear(RequestDefinition requestDefinition, ClearType type) Clear expectations, logs or both that match the request matcherClear all service-scoped chaos profiles.Retrieve the current clock status including the current instant, epoch millis, and whether the clock is frozen.voidclose()crud(CrudExpectationsDefinition crudDefinition) Register a CRUD simulation that auto-generates RESTful endpoints for a given base path.debugMismatch(RequestDefinition requestDefinition) Analyze why a request does not match any active expectations, showing per-field match failures for each expectation.Freeze the MockServer clock at the current time.freezeClock(Instant instant) Freeze the MockServer clock at the specified instant.getPort()booleanReturns whether MockServer has started, if called after MockServer has been stopped this method will block for 5 seconds while confirming MockServer is not startingbooleanhasStarted(int attempts, long timeout, TimeUnit timeUnit) Returns whether server MockServer has started, by polling the MockServer a configurable amount of timesbooleanReturns whether MockServer has stopped, if called too quickly after starting MockServer this may return false because MockServer has not yet started, to ensure MockServer has started use hasStarted()booleanhasStopped(int attempts, long timeout, TimeUnit timeUnit) Returns whether server MockServer has stopped, by polling the MockServer a configurable amount of times.booleanDeprecated.use hasStopped() or hasStarted() insteadbooleanDeprecated.use hasStopped() or hasStarted() insteadbooleanisSecure()loadAsyncApi(String specOrWrappedJson) Load an AsyncAPI spec into MockServer to start async messaging mocking.openUI()Launch UI and wait the default period to allow the UI to launch and start collecting logs, this ensures that the log are visible in the UI even if MockServer is shutdown by a test shutdown function, such as After, AfterClass, AfterAll, etcLaunch UI and wait a specified period to allow the UI to launch and start collecting logs, this ensures that the log are visible in the UI even if MockServer is shutdown by a test shutdown function, such as After, AfterClass, AfterAll, etcremoveServiceChaos(String host) Remove the service-scoped chaos profile registered for the given host.reset()Reset MockServer by clearing all expectationsReset the MockServer clock to real wall-clock time.retrieveActiveExpectations(RequestDefinition requestDefinition) Retrieve the active expectations match the httpRequest parameter, use null for the parameter to retrieve all expectationsretrieveActiveExpectations(RequestDefinition requestDefinition, Format format) Retrieve the active expectations match the httpRequest parameter, use null for the parameter to retrieve all expectationsLogEntry[]retrieveLogEntries(RequestDefinition requestDefinition) Retrieve log entries as typed objects that match the httpRequest parameter, use null for the parameter to retrieve all log entries.LogEntry[]retrieveLogEntries(RequestDefinition requestDefinition, long fromEpochMillis, long toEpochMillis) Retrieve log entries as typed objects that match the httpRequest parameter, filtered to a time window.LogEntry[]retrieveLogEntriesByCorrelationId(String correlationId) Retrieve log entries as typed objects filtered by correlation ID.retrieveLogMessages(RequestDefinition requestDefinition) Retrieve the logs associated to a specific requests, this shows all logs for expectation matching, verification, clearing, etcString[]retrieveLogMessagesArray(RequestDefinition requestDefinition) Retrieve the logs associated to a specific requests, this shows all logs for expectation matching, verification, clearing, etcretrieveLogsByCorrelationId(String correlationId) Retrieve all log entries that share the specified correlationId.retrieveRecordedExpectations(RequestDefinition requestDefinition) Retrieve the request-response combinations that have been recorded as a list of expectations, only those that match the httpRequest parameter are returned, use null to retrieve all requestsretrieveRecordedExpectations(RequestDefinition requestDefinition, Format format) Retrieve the request-response combinations that have been recorded as a list of expectations, only those that match the httpRequest parameter are returned, use null to retrieve all requestsretrieveRecordedRequests(RequestDefinition requestDefinition) Retrieve the recorded requests that match the httpRequest parameter, use null for the parameter to retrieve all requestsretrieveRecordedRequests(RequestDefinition requestDefinition, Format format) Retrieve the recorded requests that match the httpRequest parameter, use null for the parameter to retrieve all requestsretrieveRecordedRequestsAndResponses(RequestDefinition requestDefinition) Retrieve the recorded requests and responses that match the httpRequest parameter, use null for the parameter to retrieve all requests and responsesretrieveRecordedRequestsAndResponses(RequestDefinition requestDefinition, Format format) Retrieve the recorded requests that match the httpRequest parameter, use null for the parameter to retrieve all requestssendExpectation(Expectation... expectations) Deprecated.this is deprecated due to unclear naming, use method upsert(Expectation... expectations) insteadRetrieve the current service-scoped chaos registrations as a JSON string ({"services":{host: profile, ...}}).setProxyConfiguration(ProxyConfiguration proxyConfiguration) Deprecated.use withProxyConfiguration which is more consistent with MockServer API stylesetRequestOverride(HttpRequest requestOverride) Deprecated.use withRequestOverride which is more consistent with MockServer API stylesetServiceChaos(String host, HttpChaosProfile chaos) Register a service-scoped HTTP chaos profile for an upstream host.setServiceChaos(String host, HttpChaosProfile chaos, long ttlMillis) Register a service-scoped HTTP chaos profile for an upstream host that auto-reverts afterttlMillismilliseconds (a "dead-man's switch" so the chaos self-heals even ifremoveServiceChaos(String)/clearServiceChaos()is never called).voidstop()Stop MockServer gracefully (only support for Netty version, not supported for WAR version)stop(boolean ignoreFailure) Stop MockServer gracefully (only support for Netty version, not supported for WAR version)Stop MockServer gracefully (only support for Netty version, not supported for WAR version)updateConfiguration(String configurationJson) uploadGrpcDescriptor(byte[] descriptorSetBytes) upsert(Expectation... expectations) Specify one or more expectations to be create, or updated (if the id matches).upsert(OpenAPIExpectation... openAPIExpectations) Specify OpenAPI and operations and responses to create matchers and example responsesverify(Integer maximumNumberOfRequestToReturnInVerificationFailure, ExpectationId... expectationIds) Verify a list of requests have been sent in the order specified for example:verify(Integer maximumNumberOfRequestToReturnInVerificationFailure, RequestDefinition... requestDefinitions) Verify a list of requests have been sent in the order specified for example:Verify a list of requests have been sent in the order specified for example:verify(String expectationId, VerificationTimes times) Verify a request has been sent for example:verify(ExpectationId... expectationIds) Verify a list of requests have been sent in the order specified for example:verify(ExpectationId expectationId, VerificationTimes times) Verify a request has been sent for example:verify(ExpectationId expectationId, VerificationTimes times, Integer maximumNumberOfRequestToReturnInVerificationFailure) Verify a request has been sent for example:verify(RequestDefinition... requestDefinitions) Verify a list of requests have been sent in the order specified for example:verify(RequestDefinition requestDefinition, VerificationTimes times) Verify a request has been sent for example:verify(RequestDefinition requestDefinition, VerificationTimes times, Integer maximumNumberOfRequestToReturnInVerificationFailure) Verify a request has been sent for example:verifyAsyncMessage(String verificationJson) Verify async messages recorded by subscribers against the given criteria.Verify no requests have been sent.when(RequestDefinition requestDefinition) Specify an unlimited expectation that will respond regardless of the number of matching http for example:when(RequestDefinition requestDefinition, Times times) Specify a limited expectation that will respond a specified number of times when the http is matchedwhen(RequestDefinition requestDefinition, Times times, TimeToLive timeToLive) Specify a limited expectation that will respond a specified number of times when the http is matchedwhen(RequestDefinition requestDefinition, Times times, TimeToLive timeToLive, Integer priority) Specify a limited expectation that will respond a specified number of times when the http is matched and will be matched according to priority as follows:withControlPlaneJWT(String controlPlaneJWT) Specify JWT to use for control plane authorisationwithControlPlaneJWT(Supplier<String> controlPlaneJWTSupplier) Specify JWT supplier to use for control plane authorisationwithProxyConfiguration(ProxyConfiguration proxyConfiguration) Configure communication to MockServer to go via a proxywithRequestOverride(HttpRequest requestOverride) withSecure(boolean secure)
-
Field Details
-
portFuture
-
-
Constructor Details
-
MockServerClient
Start the client communicating to a MockServer on localhost at the port specified with the Future- Parameters:
portFuture- the port for the MockServer to communicate with
-
MockServerClient
Start the client communicating to a MockServer on localhost at the port specified with the Future- Parameters:
portFuture- the port for the MockServer to communicate with
-
MockServerClient
Start the client communicating to a MockServer at the specified host and port for example:MockServerClient mockServerClient = new MockServerClient("localhost", 1080);
- Parameters:
host- the host for the MockServer to communicate withport- the port for the MockServer to communicate with
-
MockServerClient
Start the client communicating to a MockServer at the specified host and port for example:MockServerClient mockServerClient = new MockServerClient("localhost", 1080);
- Parameters:
host- the host for the MockServer to communicate withport- the port for the MockServer to communicate with
-
MockServerClient
Start the client communicating to a MockServer at the specified host and port for example:MockServerClient mockServerClient = new MockServerClient("localhost", 1080);
- Parameters:
host- the host for the MockServer to communicate withport- the port for the MockServer to communicate with
-
MockServerClient
Start the client communicating to a MockServer at the specified host and port and contextPath for example:MockServerClient mockServerClient = new MockServerClient("localhost", 1080, "/mockserver");
- Parameters:
host- the host for the MockServer to communicate withport- the port for the MockServer to communicate withcontextPath- the context path that the MockServer war is deployed to
-
MockServerClient
Start the client communicating to a MockServer at the specified host and port and contextPath for example:MockServerClient mockServerClient = new MockServerClient("localhost", 1080, "/mockserver");
- Parameters:
host- the host for the MockServer to communicate withport- the port for the MockServer to communicate withcontextPath- the context path that the MockServer war is deployed to
-
MockServerClient
public MockServerClient(ClientConfiguration configuration, String host, int port, String contextPath) Start the client communicating to a MockServer at the specified host and port and contextPath for example:MockServerClient mockServerClient = new MockServerClient("localhost", 1080, "/mockserver");
- Parameters:
host- the host for the MockServer to communicate withport- the port for the MockServer to communicate withcontextPath- the context path that the MockServer war is deployed to
-
-
Method Details
-
setProxyConfiguration
Deprecated.use withProxyConfiguration which is more consistent with MockServer API style -
withProxyConfiguration
Configure communication to MockServer to go via a proxy -
withControlPlaneJWT
Specify JWT to use for control plane authorisation -
withControlPlaneJWT
Specify JWT supplier to use for control plane authorisation -
setRequestOverride
Deprecated.use withRequestOverride which is more consistent with MockServer API style -
withRequestOverride
-
isSecure
public boolean isSecure() -
withSecure
-
remoteAddress
-
contextPath
-
getPort
-
openUI
Launch UI and wait the default period to allow the UI to launch and start collecting logs, this ensures that the log are visible in the UI even if MockServer is shutdown by a test shutdown function, such as After, AfterClass, AfterAll, etc -
openUI
Launch UI and wait a specified period to allow the UI to launch and start collecting logs, this ensures that the log are visible in the UI even if MockServer is shutdown by a test shutdown function, such as After, AfterClass, AfterAll, etc- Parameters:
timeUnit- TimeUnit the time unit, for example TimeUnit.SECONDSpause- the number of time units to delay before the function returns to ensure the UI is receiving logs
-
isRunning
Deprecated.use hasStopped() or hasStarted() insteadReturns whether MockServer is running, if called too quickly after starting MockServer this may return false because MockServer has not yet started, to ensure MockServer has started use hasStarted() -
isRunning
Deprecated.use hasStopped() or hasStarted() insteadReturns whether server MockServer is running, by polling the MockServer a configurable amount of times. If called too quickly after starting MockServer this may return false because MockServer has not yet started, to ensure MockServer has started use hasStarted() -
hasStopped
public boolean hasStopped()Returns whether MockServer has stopped, if called too quickly after starting MockServer this may return false because MockServer has not yet started, to ensure MockServer has started use hasStarted() -
hasStopped
Returns whether server MockServer has stopped, by polling the MockServer a configurable amount of times. If called too quickly after starting MockServer this may return false because MockServer has not yet started, to ensure MockServer has started use hasStarted() -
hasStarted
public boolean hasStarted()Returns whether MockServer has started, if called after MockServer has been stopped this method will block for 5 seconds while confirming MockServer is not starting -
hasStarted
Returns whether server MockServer has started, by polling the MockServer a configurable amount of times -
bind
Bind new ports to listen on -
stopAsync
Stop MockServer gracefully (only support for Netty version, not supported for WAR version) -
stop
public void stop()Stop MockServer gracefully (only support for Netty version, not supported for WAR version) -
stop
Stop MockServer gracefully (only support for Netty version, not supported for WAR version) -
close
public void close()- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-
reset
Reset MockServer by clearing all expectations -
clear
Clear all expectations and logs that match the request matcher- Parameters:
requestDefinition- the http request that is matched against when deciding whether to clear each expectation if null all expectations are cleared
-
clear
Clear all expectations and logs that match the expectation id- Parameters:
expectationId- the expectation id that is used to clear expectations and logs
-
clear
Clear all expectations and logs that match the expectation id- Parameters:
expectationId- the expectation id that is used to clear expectations and logs
-
clear
Clear expectations, logs or both that match the request matcher- Parameters:
requestDefinition- the http request that is matched against when deciding whether to clear each expectation if null all expectations are clearedtype- the type to clear, EXPECTATION, LOG or BOTH
-
clear
Clear expectations, logs or both that match the expectation id- Parameters:
expectationId- the expectation id that is used to clear expectations and logstype- the type to clear, EXPECTATION, LOG or BOTH
-
clear
Clear expectations, logs or both that match the expectation id- Parameters:
expectationId- the expectation id that is used to clear expectations and logstype- the type to clear, EXPECTATION, LOG or BOTH
-
verify
Verify a list of requests have been sent in the order specified for example:mockServerClient .verify( request() .withPath("/first_request") .withBody("some_request_body"), request() .withPath("/second_request") .withBody("some_request_body") );- Parameters:
requestDefinitions- the http requests that must be matched for this verification to pass- Throws:
AssertionError- if the request has not been found
-
verify
public MockServerClient verify(Integer maximumNumberOfRequestToReturnInVerificationFailure, RequestDefinition... requestDefinitions) throws AssertionError Verify a list of requests have been sent in the order specified for example:mockServerClient .verify( request() .withPath("/first_request") .withBody("some_request_body"), request() .withPath("/second_request") .withBody("some_request_body") );- Parameters:
maximumNumberOfRequestToReturnInVerificationFailure- the maximum number requests return in the error response when the verification failsrequestDefinitions- the http requests that must be matched for this verification to pass- Throws:
AssertionError- if the request has not been found
-
verify
Verify a list of requests have been sent in the order specified for example:mockServerClient .verify( request() .withPath("/first_request") .withBody("some_request_body"), request() .withPath("/second_request") .withBody("some_request_body") );- Parameters:
expectationIds- the http requests that must be matched for this verification to pass- Throws:
AssertionError- if the request has not been found
-
verify
Verify a list of requests have been sent in the order specified for example:mockServerClient .verify( request() .withPath("/first_request") .withBody("some_request_body"), request() .withPath("/second_request") .withBody("some_request_body") );- Parameters:
expectationIds- the http requests that must be matched for this verification to pass- Throws:
AssertionError- if the request has not been found
-
verify
public MockServerClient verify(Integer maximumNumberOfRequestToReturnInVerificationFailure, ExpectationId... expectationIds) throws AssertionError Verify a list of requests have been sent in the order specified for example:mockServerClient .verify( request() .withPath("/first_request") .withBody("some_request_body"), request() .withPath("/second_request") .withBody("some_request_body") );- Parameters:
maximumNumberOfRequestToReturnInVerificationFailure- the maximum number requests return in the error response when the verification failsexpectationIds- the http requests that must be matched for this verification to pass- Throws:
AssertionError- if the request has not been found
-
verify
public MockServerClient verify(RequestDefinition requestDefinition, VerificationTimes times) throws AssertionError Verify a request has been sent for example:mockServerClient .verify( request() .withPath("/some_path") .withBody("some_request_body"), VerificationTimes.exactly(3) );VerificationTimes supports multiple static factory methods:once() - verify the request was only received once exactly(n) - verify the request was only received exactly n times atLeast(n) - verify the request was only received at least n times
- Parameters:
requestDefinition- the http request that must be matched for this verification to passtimes- the number of times this request must be matched- Throws:
AssertionError- if the request has not been found
-
verify
public MockServerClient verify(RequestDefinition requestDefinition, VerificationTimes times, Integer maximumNumberOfRequestToReturnInVerificationFailure) throws AssertionError Verify a request has been sent for example:mockServerClient .verify( request() .withPath("/some_path") .withBody("some_request_body"), VerificationTimes.exactly(3) );VerificationTimes supports multiple static factory methods:once() - verify the request was only received once exactly(n) - verify the request was only received exactly n times atLeast(n) - verify the request was only received at least n times
- Parameters:
requestDefinition- the http request that must be matched for this verification to passtimes- the number of times this request must be matchedmaximumNumberOfRequestToReturnInVerificationFailure- the maximum number requests return in the error response when the verification fails- Throws:
AssertionError- if the request has not been found
-
verify
Verify a request has been sent for example:mockServerClient .verify( request() .withPath("/some_path") .withBody("some_request_body"), VerificationTimes.exactly(3) );VerificationTimes supports multiple static factory methods:once() - verify the request was only received once exactly(n) - verify the request was only received exactly n times atLeast(n) - verify the request was only received at least n times
- Parameters:
expectationId- the http request that must be matched for this verification to passtimes- the number of times this request must be matched- Throws:
AssertionError- if the request has not been found
-
verify
public MockServerClient verify(ExpectationId expectationId, VerificationTimes times) throws AssertionError Verify a request has been sent for example:mockServerClient .verify( request() .withPath("/some_path") .withBody("some_request_body"), VerificationTimes.exactly(3) );VerificationTimes supports multiple static factory methods:once() - verify the request was only received once exactly(n) - verify the request was only received exactly n times atLeast(n) - verify the request was only received at least n times
- Parameters:
expectationId- the http request that must be matched for this verification to passtimes- the number of times this request must be matched- Throws:
AssertionError- if the request has not been found
-
verify
public MockServerClient verify(ExpectationId expectationId, VerificationTimes times, Integer maximumNumberOfRequestToReturnInVerificationFailure) throws AssertionError Verify a request has been sent for example:mockServerClient .verify( request() .withPath("/some_path") .withBody("some_request_body"), VerificationTimes.exactly(3) );VerificationTimes supports multiple static factory methods:once() - verify the request was only received once exactly(n) - verify the request was only received exactly n times atLeast(n) - verify the request was only received at least n times
- Parameters:
expectationId- the http request that must be matched for this verification to passtimes- the number of times this request must be matchedmaximumNumberOfRequestToReturnInVerificationFailure- the maximum number requests return in the error response when the verification fails- Throws:
AssertionError- if the request has not been found
-
verifyZeroInteractions
Verify no requests have been sent.- Throws:
AssertionError- if any request has been found
-
retrieveRecordedRequests
Retrieve the recorded requests that match the httpRequest parameter, use null for the parameter to retrieve all requests- Parameters:
requestDefinition- the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requests- Returns:
- an array of all requests that have been recorded by the MockServer in the order they have been received and including duplicates where the same request has been received multiple times
-
retrieveRecordedRequests
Retrieve the recorded requests that match the httpRequest parameter, use null for the parameter to retrieve all requests- Parameters:
requestDefinition- the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requestsformat- the format to retrieve the expectations, either JAVA or JSON- Returns:
- an array of all requests that have been recorded by the MockServer in the order they have been received and including duplicates where the same request has been received multiple times
-
retrieveRecordedRequestsAndResponses
public LogEventRequestAndResponse[] retrieveRecordedRequestsAndResponses(RequestDefinition requestDefinition) Retrieve the recorded requests and responses that match the httpRequest parameter, use null for the parameter to retrieve all requests and responses- Parameters:
requestDefinition- the http request that is matched against when deciding whether to return each request (and its corresponding response), use null for the parameter to retrieve for all requests- Returns:
- an array of all requests and responses that have been recorded by the MockServer in the order they have been received and including duplicates where the same request has been received multiple times
-
retrieveRecordedRequestsAndResponses
public String retrieveRecordedRequestsAndResponses(RequestDefinition requestDefinition, Format format) Retrieve the recorded requests that match the httpRequest parameter, use null for the parameter to retrieve all requests- Parameters:
requestDefinition- the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requestsformat- the format to retrieve the expectations, either JAVA or JSON- Returns:
- an array of all requests that have been recorded by the MockServer in the order they have been received and including duplicates where the same request has been received multiple times
-
retrieveRecordedExpectations
Retrieve the request-response combinations that have been recorded as a list of expectations, only those that match the httpRequest parameter are returned, use null to retrieve all requests- Parameters:
requestDefinition- the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requests- Returns:
- an array of all expectations that have been recorded by the MockServer in the order they have been received and including duplicates where the same request has been received multiple times
-
retrieveRecordedExpectations
Retrieve the request-response combinations that have been recorded as a list of expectations, only those that match the httpRequest parameter are returned, use null to retrieve all requests- Parameters:
requestDefinition- the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requestsformat- the format to retrieve the expectations, either JAVA or JSON- Returns:
- an array of all expectations that have been recorded by the MockServer in the order they have been received and including duplicates where the same request has been received multiple times
-
retrieveLogMessages
Retrieve the logs associated to a specific requests, this shows all logs for expectation matching, verification, clearing, etc- Parameters:
requestDefinition- the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requests- Returns:
- all log messages recorded by the MockServer when creating expectations, matching expectations, performing verification, clearing logs, etc
-
retrieveLogMessagesArray
Retrieve the logs associated to a specific requests, this shows all logs for expectation matching, verification, clearing, etc- Parameters:
requestDefinition- the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requests- Returns:
- an array of all log messages recorded by the MockServer when creating expectations, matching expectations, performing verification, clearing logs, etc
-
retrieveLogEntries
Retrieve log entries as typed objects that match the httpRequest parameter, use null for the parameter to retrieve all log entries. Uses the LOG_ENTRIES format to get structured JSON log entries from the server.- Parameters:
requestDefinition- the http request that is matched against when deciding whether to return each log entry, use null to retrieve all- Returns:
- an array of all log entries that match
-
retrieveLogEntriesByCorrelationId
Retrieve log entries as typed objects filtered by correlation ID. A correlationId groups all log entries for a single incoming HTTP request lifecycle.- Parameters:
correlationId- the correlation ID to filter by- Returns:
- an array of all log entries for the given correlation ID
-
retrieveLogEntries
public LogEntry[] retrieveLogEntries(RequestDefinition requestDefinition, long fromEpochMillis, long toEpochMillis) Retrieve log entries as typed objects that match the httpRequest parameter, filtered to a time window. Only entries with epochTime between fromEpochMillis (inclusive) and toEpochMillis (exclusive) are returned. Note: time filtering is performed client-side after fetching all matching entries from the server.- Parameters:
requestDefinition- the http request that is matched against when deciding whether to return each log entry, use null to retrieve allfromEpochMillis- start of time window (inclusive), milliseconds since epochtoEpochMillis- end of time window (exclusive), milliseconds since epoch- Returns:
- an array of log entries within the specified time window
-
when
Specify an unlimited expectation that will respond regardless of the number of matching http for example:mockServerClient .when( request() .withPath("/some_path") .withBody("some_request_body") ) .respond( response() .withBody("some_response_body") .withHeader("responseName", "responseValue") )- Parameters:
requestDefinition- the http request that must be matched for this expectation to respond- Returns:
- an Expectation object that can be used to specify the response
-
when
Specify a limited expectation that will respond a specified number of times when the http is matchedExample use:
mockServerClient .when( request() .withPath("/some_path") .withBody("some_request_body"), Times.exactly(5) ) .respond( response() .withBody("some_response_body") .withHeader("responseName", "responseValue") )- Parameters:
requestDefinition- the http request that must be matched for this expectation to respondtimes- the number of times to respond when this http is matched- Returns:
- an Expectation object that can be used to specify the response
-
when
public ForwardChainExpectation when(RequestDefinition requestDefinition, Times times, TimeToLive timeToLive) Specify a limited expectation that will respond a specified number of times when the http is matchedExample use:
mockServerClient .when( request() .withPath("/some_path") .withBody("some_request_body"), Times.exactly(5), TimeToLive.exactly(TimeUnit.SECONDS, 120) ) .respond( response() .withBody("some_response_body") .withHeader("responseName", "responseValue") )- Parameters:
requestDefinition- the http request that must be matched for this expectation to respondtimes- the number of times to respond when this http is matchedtimeToLive- the length of time from when the server receives the expectation that the expectation should be active- Returns:
- an Expectation object that can be used to specify the response
-
when
public ForwardChainExpectation when(RequestDefinition requestDefinition, Times times, TimeToLive timeToLive, Integer priority) Specify a limited expectation that will respond a specified number of times when the http is matched and will be matched according to priority as follows:- higher priority expectation will be matched first - identical priority expectations will be match in the order they were submitted - default priority is 0
Example use:
mockServerClient .when( request() .withPath("/some_path") .withBody("some_request_body"), Times.exactly(5), TimeToLive.exactly(TimeUnit.SECONDS, 120), 10 ) .respond( response() .withBody("some_response_body") .withHeader("responseName", "responseValue") )- Parameters:
requestDefinition- the http request that must be matched for this expectation to respondtimes- the number of times to respond when this http is matchedtimeToLive- the length of time from when the server receives the expectation that the expectation should be activepriority- the priority for the expectation when matching, higher priority expectation will be matched first, identical priority expectations will be match in the order they were submitted- Returns:
- an Expectation object that can be used to specify the response
-
upsert
Specify OpenAPI and operations and responses to create matchers and example responses- Parameters:
openAPIExpectations- the OpenAPI and operations and responses to create matchers and example responses- Returns:
- upserted expectations
-
upsert
Specify one or more expectations to be create, or updated (if the id matches).This method should be used to update existing expectation by id. All fields will be updated for expectations with a matching id as the existing expectation is deleted and recreated.
To retrieve the id(s) for existing expectation(s) the retrieveActiveExpectations(HttpRequest httpRequest) method can be used.
Typically, to create expectations this method should not be used directly instead the when(...) and response(...) or forward(...) or error(...) methods should be used for example:
mockServerClient .when( request() .withPath("/some_path") .withBody("some_request_body"), Times.exactly(5), TimeToLive.exactly(TimeUnit.SECONDS, 120) ) .respond( response() .withBody("some_response_body") .withHeader("responseName", "responseValue") )- Parameters:
expectations- one or more expectations to create or update (if the id field matches)- Returns:
- upserted expectations
-
crud
Register a CRUD simulation that auto-generates RESTful endpoints for a given base path.For example, with basePath "/api/users", MockServer will automatically handle:
- GET /api/users - list all items
- POST /api/users - create a new item
- GET /api/users/{id} - get an item by ID
- PUT /api/users/{id} - update an item by ID
- DELETE /api/users/{id} - delete an item by ID
- Parameters:
crudDefinition- the CRUD expectations definition specifying basePath, idField, idStrategy, and optional initial data- Returns:
- this MockServerClient for fluent chaining
-
sendExpectation
Deprecated.this is deprecated due to unclear naming, use method upsert(Expectation... expectations) insteadSpecify one or more expectations, normally this method should not be used directly instead the when(...) and response(...) or forward(...) or error(...) methods should be used for example:mockServerClient .when( request() .withPath("/some_path") .withBody("some_request_body"), Times.exactly(5), TimeToLive.exactly(TimeUnit.SECONDS, 120) ) .respond( response() .withBody("some_response_body") .withHeader("responseName", "responseValue") )- Parameters:
expectations- one or more expectations- Returns:
- added or updated expectations
-
retrieveActiveExpectations
Retrieve the active expectations match the httpRequest parameter, use null for the parameter to retrieve all expectations- Parameters:
requestDefinition- the http request that is matched against when deciding whether to return each expectation, use null for the parameter to retrieve for all requests- Returns:
- an array of all expectations that have been setup and have not expired
-
retrieveActiveExpectations
Retrieve the active expectations match the httpRequest parameter, use null for the parameter to retrieve all expectations- Parameters:
requestDefinition- the http request that is matched against when deciding whether to return each expectation, use null for the parameter to retrieve for all requestsformat- the format to retrieve the expectations, either JAVA or JSON- Returns:
- an array of all expectations that have been setup and have not expired
-
debugMismatch
Analyze why a request does not match any active expectations, showing per-field match failures for each expectation. Returns a JSON string containing the total number of expectations, the closest match, and per-expectation results with field-level differences.- Parameters:
requestDefinition- the request to debug against active expectations- Returns:
- a JSON string with structured match analysis
-
retrieveLogsByCorrelationId
Retrieve all log entries that share the specified correlationId. A correlationId groups all log entries for a single incoming HTTP request lifecycle (received, match attempts, response).- Parameters:
correlationId- the correlation ID to filter by- Returns:
- a string containing all log entries for the given correlation ID
-
retrieveMetrics
-
retrieveConfiguration
-
updateConfiguration
-
uploadGrpcDescriptor
-
retrieveGrpcServices
-
clearGrpcDescriptors
-
freezeClock
Freeze the MockServer clock at the specified instant.- Parameters:
instant- the instant to freeze the clock at- Returns:
- this MockServerClient
-
freezeClock
Freeze the MockServer clock at the current time.- Returns:
- this MockServerClient
-
advanceClock
Advance the MockServer clock by the specified duration.- Parameters:
duration- the duration to advance the clock by- Returns:
- this MockServerClient
-
resetClock
Reset the MockServer clock to real wall-clock time.- Returns:
- this MockServerClient
-
clockStatus
Retrieve the current clock status including the current instant, epoch millis, and whether the clock is frozen.- Returns:
- JSON string with fields: currentInstant, currentEpochMillis, frozen
-
setServiceChaos
Register a service-scoped HTTP chaos profile for an upstream host. The profile is applied to every matched forward expectation to that host that does not define its ownchaosblock (an expectation's own chaos always wins). The host is matched case-insensitively, ignoring any:port. SeePUT /mockserver/serviceChaos.- Parameters:
host- the upstream host to breakchaos- the chaos profile to apply to that host's forwarded responses- Returns:
- this MockServerClient
-
setServiceChaos
Register a service-scoped HTTP chaos profile for an upstream host that auto-reverts afterttlMillismilliseconds (a "dead-man's switch" so the chaos self-heals even ifremoveServiceChaos(String)/clearServiceChaos()is never called). SeePUT /mockserver/serviceChaos.- Parameters:
host- the upstream host to breakchaos- the chaos profile to apply to that host's forwarded responsesttlMillis- milliseconds after which the chaos auto-reverts;<= 0means no expiry- Returns:
- this MockServerClient
-
removeServiceChaos
Remove the service-scoped chaos profile registered for the given host.- Parameters:
host- the upstream host whose service-scoped chaos should be removed- Returns:
- this MockServerClient
-
clearServiceChaos
Clear all service-scoped chaos profiles.- Returns:
- this MockServerClient
-
serviceChaosStatus
Retrieve the current service-scoped chaos registrations as a JSON string ({"services":{host: profile, ...}}).- Returns:
- JSON string of the current host → profile registrations
-
loadAsyncApi
Load an AsyncAPI spec into MockServer to start async messaging mocking. The body can be either a plain AsyncAPI document (JSON or YAML) or a wrapped body:{"spec": <spec>, "brokerConfig": {...}}.- Parameters:
specOrWrappedJson- the AsyncAPI spec or wrapped JSON body- Returns:
- the JSON response from the server describing the loaded spec
-
asyncApiStatus
Retrieve the current AsyncAPI mocking status including loaded spec info, active channels, and recorded messages.- Returns:
- JSON string of the current async mocking status
-
verifyAsyncMessage
Verify async messages recorded by subscribers against the given criteria. The verification JSON must contain at least achannelfield, and optionallypayloadSubstring,payloadJsonPath,expectedValue, andcount(withatLeast,atMost, orexactly).- Parameters:
verificationJson- the verification criteria as JSON- Throws:
AssertionError- if the verification fails (server responds with 406)
-