Class MockServerClient
- All Implemented Interfaces:
Closeable,AutoCloseable,Stoppable
- Direct Known Subclasses:
ClientAndServer
- Author:
- jamesdbloom
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final recordA scenario and its current state, as returned by the scenario control-plane endpoints.classTyped handle that wraps the scenario control-plane endpoints for a single named scenario. -
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 TypeMethodDescriptionaddBreakpoint(RequestDefinition matcher, Set<BreakpointPhase> phases, BreakpointRequestHandler requestHandler, BreakpointResponseHandler responseHandler, BreakpointStreamFrameHandler streamFrameHandler) Register a breakpoint matcher with request/response/stream-frame handlers.addBreakpoint(RequestDefinition matcher, Set<BreakpointPhase> phases, BreakpointStreamFrameHandler streamFrameHandler) Register a breakpoint matcher with a stream frame handler.addBreakpoint(RequestDefinition matcher, BreakpointRequestHandler requestHandler) Register a breakpoint matcher with a single request handler (REQUEST phase only).addBreakpoint(RequestDefinition matcher, BreakpointRequestHandler requestHandler, BreakpointResponseHandler responseHandler) Register a breakpoint matcher with request and response handlers.addBreakpoint(RequestDefinition matcher, BreakpointRequestHandler requestHandler, BreakpointResponseHandler responseHandler, BreakpointStreamFrameHandler streamFrameHandler, BreakpointPhase... phases) Register a breakpoint matcher with varargs phases and all handlers.advanceClock(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 registered breakpoint matchers.clearByNamespace(String namespace) Clear only the expectations belonging to a single namespace (tenant), leaving expectations in other namespaces and global (no-namespace) expectations intact.Remove all registered load scenarios viaDELETE /mockserver/loadScenario.Clear 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.deleteLoadScenario(String name) Remove a single registered load scenario by name viaDELETE /mockserver/loadScenario/{name}.Freeze the MockServer clock at the current time.freezeClock(Instant instant) Freeze the MockServer clock at the specified instant.getLoadScenario(String name) Retrieve a single registered load scenario by name viaGET /mockserver/loadScenario/{name}.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.importExpectations(String expectationsJson) Import one or more expectations from a JSON document into a running MockServer.importExpectationsFromFile(String filePath) Import one or more expectations from a JSON file into a running MockServer.booleanDeprecated.use hasStopped() or hasStarted() insteadbooleanDeprecated.use hasStopped() or hasStarted() insteadbooleanisSecure()List all registered breakpoint matchers.loadAsyncApi(String specOrWrappedJson) Load an AsyncAPI spec into MockServer to start async messaging mocking.loadScenario(LoadScenario scenario) Register (load) a load-injection scenario into the load-scenario registry viaPUT /mockserver/loadScenario.List all registered load scenarios viaGET /mockserver/loadScenario.Mock a complete OpenID Connect / OAuth2 identity provider with a single call, using the default configuration (issuerhttp://localhost:1080, standard endpoint paths, RS256 signing).mockOpenIdProvider(OidcProviderConfiguration configuration) Mock a complete OpenID Connect / OAuth2 identity provider with a single call.Stand up a complete mock SAML 2.0 Identity Provider with default settings: a metadata endpoint, an SP-initiated Web-Browser-SSO POST endpoint, and a Single-Logout endpoint, signed with a freshly generated self-signed RSA credential whose certificate is published in the metadata.mockSamlProvider(SamlProviderConfiguration samlProviderConfiguration) Stand up a complete mock SAML 2.0 Identity Provider from the given configuration.Register a mock SCIM 2.0 provider using the default configuration (base path/scim/v2).mockScimProvider(ScimProviderConfiguration scimConfiguration) Register a mock SCIM 2.0 provider that auto-generates a complete set of SCIM endpoints for the configured base path (default/scim/v2).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, etcRemove a breakpoint matcher by id.removeServiceChaos(String host) Remove the service-scoped chaos profile registered for the given host.replay(HttpRequest requestToReplay) Replay a request to its upstream target and return the upstream response.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, String namespace) Retrieve the active expectations visible to a single namespace (tenant): the expectations registered undernamespaceplus all global (no-namespace) expectations.retrieveActiveExpectations(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 requestsrunLoadScenario(LoadScenario scenario) Convenience helper that registers the given scenario and then immediately starts it, combiningloadScenario(LoadScenario)andstartLoadScenarios(String...).Obtain a typed handle for inspecting and driving a stateful scenario by name.List every known scenario and its current state.sendExpectation(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).startLoadScenarios(String... names) Start one or more previously-registered load scenarios by name viaPUT /mockserver/loadScenario/startwith body{"names":[...]}.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)stopLoadScenarios(String... names) Stop one or more running load scenarios viaPUT /mockserver/loadScenario/stop.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(HttpResponse httpResponse) Verify a response has been recorded (matching any request), defaulting to at least onceverify(HttpResponse httpResponse, VerificationTimes times) Verify a response has been recorded (matching any request) for example:verify(RequestDefinition... requestDefinitions) Verify a list of requests have been sent in the order specified for example:verify(RequestDefinition requestDefinition, HttpResponse httpResponse, VerificationTimes times) Verify a request-response pair has been recorded 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:verify(RequestDefinition requestDefinition, VerificationTimes times, Duration timeout) Eventual verification: poll the event log, retrying the supplied verification until it passes or the timeout expires.verify(Verification verification) Verify using a pre-built Verification object for advanced use cases such as request-response pair verification:verify(Verification verification, Duration timeout) Eventual verification: poll the event log, retrying the suppliedVerificationuntil it passes or the timeout expires.verify(VerificationSequence verificationSequence) Verify using a pre-built VerificationSequence object for advanced use cases such as request-response sequence verification:verifyAll(Verification... verifications) Verify multiple verifications, collecting all failures and throwing a singleAssertionErrorthat lists every mismatch.verifyAsyncMessage(String verificationJson) Verify async messages recorded by subscribers against the given criteria.verifyNever(RequestDefinition requestDefinition, Duration window) Negative-within-timeout verification: assert that the supplied verification stays unsatisfied for the whole window.verifyNever(Verification verification, Duration window) Negative-within-timeout verification: assert that the suppliedVerificationstays unsatisfied for the whole window.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
-
clearByNamespace
Clear only the expectations belonging to a single namespace (tenant), leaving expectations in other namespaces and global (no-namespace) expectations intact.This is the primary multi-tenancy teardown call: a CI job that registers its expectations under its own namespace can clean up after itself on a shared MockServer instance without disturbing other tenants. The event log is not namespaced, so logs are left untouched (only
expectationsare cleared).- Parameters:
namespace- the namespace (tenant) whose expectations to clear
-
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
-
verifyAll
Verify multiple verifications, collecting all failures and throwing a singleAssertionErrorthat lists every mismatch. Unlike#verify(Verification...)and the otherverify(...)methods (which throw on the first failure), this runs every suppliedVerificationand only throws once all have been evaluated, so a test sees all failures at once. For example:mockServerClient .verifyAll( verification().withRequest(request().withPath("/one")).withTimes(once()), verification().withRequest(request().withPath("/two")).withTimes(once()) );- Parameters:
verifications- the verifications that must all pass- Throws:
AssertionError- if any verification fails, with a message listing every failure
-
verifyZeroInteractions
Verify no requests have been sent.- Throws:
AssertionError- if any request has been found
-
verify
public MockServerClient verify(RequestDefinition requestDefinition, VerificationTimes times, Duration timeout) throws AssertionError Eventual verification: poll the event log, retrying the supplied verification until it passes or the timeout expires. This is useful when the application under test sends requests asynchronously (fire-and-forget, background workers), so the request may not have arrived at MockServer at the instant the test calls verify. Instead of a single snapshot check (likeverify(Verification)), this re-runs the verification with a small backoff until it passes or the window elapses, throwing the last failure on timeout.mockServerClient .verify( request().withPath("/some_path"), VerificationTimes.once(), Duration.ofSeconds(5) );This is implemented purely client-side (a poll loop over the standard verify endpoint); no server-side change or wait is involved.- Parameters:
requestDefinition- the http request that must be matched for this verification to passtimes- the number of times this request must be matchedtimeout- the maximum time to wait for the verification to pass- Throws:
AssertionError- if the verification does not pass before the timeout expires
-
verify
Eventual verification: poll the event log, retrying the suppliedVerificationuntil it passes or the timeout expires. Seeverify(RequestDefinition, VerificationTimes, Duration)for the rationale; this generic overload accepts a fully builtVerification(so it also covers response and expectation-id verifications).mockServerClient .verify( verification() .withRequest(request().withPath("/some_path")) .withTimes(VerificationTimes.atLeast(1)), Duration.ofSeconds(5) );- Parameters:
verification- the verification object containing the request, response, and/or times to verifytimeout- the maximum time to wait for the verification to pass- Throws:
AssertionError- if the verification does not pass before the timeout expires
-
verifyNever
public MockServerClient verifyNever(RequestDefinition requestDefinition, Duration window) throws AssertionError Negative-within-timeout verification: assert that the supplied verification stays unsatisfied for the whole window. This is useful for asserting "no matching request was made within N seconds" — the opposite of eventual verification. The verification is polled repeatedly for the duration of the window; if it ever passes (the condition becomes met), anAssertionErroris thrown immediately. If the window elapses without the verification ever passing, the method returns normally.mockServerClient .verifyNever( request().withPath("/should_not_be_called"), Duration.ofSeconds(2) );The supplied request is verified withVerificationTimes.atLeast(int)(1)— i.e. the window fails the moment one matching request is observed. Implemented purely client-side (a poll loop over the standard verify endpoint).- Parameters:
requestDefinition- the http request that must not be matched during the windowwindow- the time to keep checking that no matching request arrives- Throws:
AssertionError- if a matching request is observed before the window elapses
-
verifyNever
public MockServerClient verifyNever(Verification verification, Duration window) throws AssertionError Negative-within-timeout verification: assert that the suppliedVerificationstays unsatisfied for the whole window. SeeverifyNever(RequestDefinition, Duration)for the rationale; this generic overload accepts a fully builtVerificationso the caller controls the matched condition (e.g.atLeast(1)to fail on the first match, or anotherVerificationTimesto fail when a threshold is reached).- Parameters:
verification- the verification that must not pass during the windowwindow- the time to keep checking that the verification does not pass- Throws:
AssertionError- if the verification passes before the window elapses
-
verify
public MockServerClient verify(RequestDefinition requestDefinition, HttpResponse httpResponse, VerificationTimes times) throws AssertionError Verify a request-response pair has been recorded for example:mockServerClient .verify( request() .withPath("/some_path"), response() .withStatusCode(200), VerificationTimes.atLeast(1) );VerificationTimes supports multiple static factory methods:once() - verify the request-response pair was matched only once exactly(n) - verify the request-response pair was matched exactly n times atLeast(n) - verify the request-response pair was matched at least n times
- Parameters:
requestDefinition- the http request that must be matched for this verification to pass (may be null to match any request)httpResponse- the http response that must be matched for this verification to passtimes- the number of times this request-response pair must be matched- Throws:
AssertionError- if the request-response pair has not been found
-
verify
public MockServerClient verify(HttpResponse httpResponse, VerificationTimes times) throws AssertionError Verify a response has been recorded (matching any request) for example:mockServerClient .verify( response() .withStatusCode(200), VerificationTimes.atLeast(1) );- Parameters:
httpResponse- the http response that must be matched for this verification to passtimes- the number of times this response must be matched- Throws:
AssertionError- if the response has not been found
-
verify
Verify a response has been recorded (matching any request), defaulting to at least oncemockServerClient .verify( response() .withStatusCode(200) );- Parameters:
httpResponse- the http response that must be matched for this verification to pass- Throws:
AssertionError- if the response has not been found
-
verify
Verify using a pre-built Verification object for advanced use cases such as request-response pair verification:mockServerClient .verify( verification() .withRequest(request().withPath("/some_path")) .withResponse(response().withStatusCode(200)) .withTimes(VerificationTimes.atLeast(1)) );- Parameters:
verification- the verification object containing the request, response, and/or times to verify- Throws:
AssertionError- if the verification fails
-
verify
Verify using a pre-built VerificationSequence object for advanced use cases such as request-response sequence verification:mockServerClient .verify( verificationSequence() .withRequests(request().withPath("/first"), request().withPath("/second")) .withResponses(response().withStatusCode(200), response().withStatusCode(201)) );- Parameters:
verificationSequence- the verification sequence object containing the requests, responses, and/or expectation ids to verify- Throws:
AssertionError- if the verification sequence fails
-
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
-
mockOpenIdProvider
Mock a complete OpenID Connect / OAuth2 identity provider with a single call, using the default configuration (issuerhttp://localhost:1080, standard endpoint paths, RS256 signing).This generates and upserts the discovery document, JWKS, token, authorize, userinfo, introspection, revocation, and end-session endpoints, all signed with a freshly generated key pair whose public key is published at the JWKS endpoint so issued tokens verify end-to-end.
- Returns:
- the upserted OIDC provider expectations
-
mockOpenIdProvider
Mock a complete OpenID Connect / OAuth2 identity provider with a single call.This generates and upserts the discovery document, JWKS, token, authorize, userinfo, introspection, revocation, and end-session endpoints. Tokens are minted at request time and signed with the configured (or generated) key pair, whose public key is published at the JWKS endpoint so issued tokens verify end-to-end. The configuration controls the issuer, endpoint paths, subject / clientId / audience / scopes, token expiry, additional claims, signing algorithm and key material, and the negative-testing flags.
- Parameters:
configuration- the OIDC provider configuration, ornullto use the defaults- Returns:
- the upserted OIDC provider expectations
-
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
-
mockSamlProvider
Stand up a complete mock SAML 2.0 Identity Provider with default settings: a metadata endpoint, an SP-initiated Web-Browser-SSO POST endpoint, and a Single-Logout endpoint, signed with a freshly generated self-signed RSA credential whose certificate is published in the metadata.- Returns:
- the upserted expectations (metadata + SSO + SLO)
-
mockSamlProvider
Stand up a complete mock SAML 2.0 Identity Provider from the given configuration. The configuration controls the IdP/SP entity ids, endpoint paths, the asserted subject and attributes, the signing algorithm, and the negative-test flags (expired assertion, wrong audience, tampered signature) for exercising an SP's rejection paths.- Parameters:
samlProviderConfiguration- the SAML provider configuration (defaults applied for unset fields)- Returns:
- the upserted expectations (metadata + SSO + SLO)
-
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
-
importExpectations
Import one or more expectations from a JSON document into a running MockServer.The JSON may be a single expectation object or an array of expectations — the same format produced by
retrieveActiveExpectations(RequestDefinition)withFormat.JSON, persisted via the--persistflag, or exported from the dashboard. Each imported expectation is created, or updated if itsidmatches an existing expectation (an upsert).- Parameters:
expectationsJson- a JSON expectation object or array of expectation objects- Returns:
- the imported (created or updated) expectations
-
importExpectationsFromFile
Import one or more expectations from a JSON file into a running MockServer.The file may contain a single expectation object or an array of expectations — the same format produced by
retrieveActiveExpectations(RequestDefinition)withFormat.JSON, persisted via the--persistflag, or exported from the dashboard. Each imported expectation is created, or updated if itsidmatches an existing expectation (an upsert). The path is resolved from the classpath or the filesystem.- Parameters:
filePath- path to a JSON file containing an expectation object or array of expectation objects- Returns:
- the imported (created or updated) 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
-
mockScimProvider
Register a mock SCIM 2.0 provider that auto-generates a complete set of SCIM endpoints for the configured base path (default/scim/v2).For example, with the default configuration MockServer will serve:
GET/POST /scim/v2/UsersandGET/PUT/PATCH/DELETE /scim/v2/Users/{id}GET/POST /scim/v2/GroupsandGET/PUT/PATCH/DELETE /scim/v2/Groups/{id}GET /scim/v2/ServiceProviderConfig,/ResourceTypes,/Schemas
application/scim+jsonmedia type, the SCIM ListResponse/Error envelopes, and injectschemas/id/metaon every resource.- Parameters:
scimConfiguration- the SCIM provider configuration (basePath, idStrategy, initial data, enforcement flags)- Returns:
- the upserted SCIM provider expectations
-
mockScimProvider
Register a mock SCIM 2.0 provider using the default configuration (base path/scim/v2).- Returns:
- the upserted SCIM provider expectations
-
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
public Expectation[] retrieveActiveExpectations(RequestDefinition requestDefinition, String namespace) Retrieve the active expectations visible to a single namespace (tenant): the expectations registered undernamespaceplus all global (no-namespace) expectations. Other tenants' expectations are hidden.Use null for
requestDefinitionto retrieve all of this namespace's expectations regardless of request matcher.- Parameters:
requestDefinition- the http request matched against when deciding whether to return each expectation, or null for allnamespace- the namespace (tenant) whose expectations to view- Returns:
- an array of the active expectations visible to the given namespace
-
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
-
loadScenario
Register (load) a load-injection scenario into the load-scenario registry viaPUT /mockserver/loadScenario. Registration does not start the scenario — it is loaded in theLOADEDstate and driving no traffic. Each scenario is identified by its uniquename; registering a scenario with an existing name replaces it.Registration is always permitted, even when
loadGenerationEnabledis off on the server — onlystartingrequires load generation to be enabled.- Parameters:
scenario- the load scenario to register (seeLoadScenario)- Returns:
- JSON string describing the registered scenario (
{"name":...,"state":...})
-
loadScenarios
List all registered load scenarios viaGET /mockserver/loadScenario. The response body is a JSON object{"scenarios":[{"name":...,"state":...,"definition":...,"status":...}]}where each entry carries the scenario name, lifecycle state (one ofLOADED,PENDING,RUNNING,COMPLETED,STOPPED), its definition, and live status for running scenarios.- Returns:
- JSON string listing all registered load scenarios
-
getLoadScenario
Retrieve a single registered load scenario by name viaGET /mockserver/loadScenario/{name}. The server responds404if no scenario with that name is registered.- Parameters:
name- the unique name of the registered load scenario- Returns:
- JSON string describing the named load scenario (name, state, definition, status)
-
deleteLoadScenario
Remove a single registered load scenario by name viaDELETE /mockserver/loadScenario/{name}. If the scenario is running it is stopped before removal.- Parameters:
name- the unique name of the load scenario to remove- Returns:
- this MockServerClient
-
clearLoadScenarios
Remove all registered load scenarios viaDELETE /mockserver/loadScenario. Any running scenarios are stopped before the registry is cleared.- Returns:
- this MockServerClient
-
startLoadScenarios
Start one or more previously-registered load scenarios by name viaPUT /mockserver/loadScenario/startwith body{"names":[...]}. Each named scenario begins running (honouring itsstartDelayMillis, which holds the scenario inPENDINGuntil the delay elapses).Starting requires
loadGenerationEnabledon the server — if it is off the server responds403and this throws aClientExceptionwith a helpful message. An unknown scenario name causes the server to respond404, which is also surfaced as aClientException.- Parameters:
names- the names of the registered scenarios to start- Returns:
- JSON string describing the started scenarios (
{"started":[...],"status":...})
-
stopLoadScenarios
Stop one or more running load scenarios viaPUT /mockserver/loadScenario/stop. Whennamesare supplied the body is{"names":[...]}and only those scenarios are stopped; when called with no arguments the body is empty, which stops all running scenarios. Stopped scenarios transition to theSTOPPEDstate but remain registered (and can be re-started).- Parameters:
names- the names of the scenarios to stop, or none to stop all running scenarios- Returns:
- JSON string describing the stopped scenarios (
{"stopped":[...],"status":...})
-
runLoadScenario
Convenience helper that registers the given scenario and then immediately starts it, combiningloadScenario(LoadScenario)andstartLoadScenarios(String...). Starting requiresloadGenerationEnabledon the server (seestartLoadScenarios(String...)for the403behaviour).- Parameters:
scenario- the load scenario to register and start- Returns:
- JSON string describing the started scenario (
{"started":[...],"status":...})
-
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)
-
addBreakpoint
public String addBreakpoint(RequestDefinition matcher, Set<BreakpointPhase> phases, BreakpointRequestHandler requestHandler, BreakpointResponseHandler responseHandler, BreakpointStreamFrameHandler streamFrameHandler) Register a breakpoint matcher with request/response/stream-frame handlers. The client's callback WebSocket is opened if not already connected.Handlers are stored per breakpoint id (the id returned by the server), so multiple concurrent breakpoints each route to their own handler. If a handler is null for a phase that is in the phase set, items for that phase will be auto-continued.
- Parameters:
matcher- the request definition to match against (same shape as an expectation request matcher)phases- the set of phases to interceptrequestHandler- handler for REQUEST phase (may be null if REQUEST not in phases)responseHandler- handler for RESPONSE phase (may be null if RESPONSE not in phases)streamFrameHandler- handler for RESPONSE_STREAM / INBOUND_STREAM phases (may be null if neither streaming phase is in phases)- Returns:
- the breakpoint matcher id assigned by the server
-
addBreakpoint
Register a breakpoint matcher with a single request handler (REQUEST phase only).- Parameters:
matcher- the request definition to match againstrequestHandler- handler for REQUEST phase breakpoints- Returns:
- the breakpoint matcher id
-
addBreakpoint
public String addBreakpoint(RequestDefinition matcher, BreakpointRequestHandler requestHandler, BreakpointResponseHandler responseHandler) Register a breakpoint matcher with request and response handlers.- Parameters:
matcher- the request definition to match againstrequestHandler- handler for REQUEST phaseresponseHandler- handler for RESPONSE phase- Returns:
- the breakpoint matcher id
-
addBreakpoint
public String addBreakpoint(RequestDefinition matcher, Set<BreakpointPhase> phases, BreakpointStreamFrameHandler streamFrameHandler) Register a breakpoint matcher with a stream frame handler.- Parameters:
matcher- the request definition to match againstphases- the set of streaming phases to interceptstreamFrameHandler- handler for RESPONSE_STREAM / INBOUND_STREAM phases- Returns:
- the breakpoint matcher id
-
addBreakpoint
public String addBreakpoint(RequestDefinition matcher, BreakpointRequestHandler requestHandler, BreakpointResponseHandler responseHandler, BreakpointStreamFrameHandler streamFrameHandler, BreakpointPhase... phases) Register a breakpoint matcher with varargs phases and all handlers. If zero phases are passed, phases are inferred from the non-null handlers: requestHandler implies REQUEST, responseHandler implies RESPONSE, streamFrameHandler implies RESPONSE_STREAM and INBOUND_STREAM.- Parameters:
matcher- the request definition to match againstrequestHandler- handler for REQUEST phase (may be null)responseHandler- handler for RESPONSE phase (may be null)streamFrameHandler- handler for streaming phases (may be null)phases- the phases to intercept (if empty, inferred from handlers)- Returns:
- the breakpoint matcher id
- Throws:
IllegalArgumentException- if no phases can be determined
-
listBreakpointMatchers
List all registered breakpoint matchers. Returns a JSON string with the structure:{ "matchers": [ { "id": "...", "httpRequest": {...}, "phases": [...], "clientId": "..." } ] }- Returns:
- JSON string describing all registered breakpoint matchers
-
removeBreakpointMatcher
Remove a breakpoint matcher by id.- Parameters:
id- the breakpoint matcher id to remove- Returns:
- this MockServerClient
- Throws:
IllegalArgumentException- if the id is blank
-
clearBreakpointMatchers
Clear all registered breakpoint matchers.- Returns:
- this MockServerClient
-
replay
Replay a request to its upstream target and return the upstream response. The request is sent exactly as specified — the target host/port is resolved from theHostheader or the explicitsocketAddressfield.- Parameters:
requestToReplay- the request to re-issue to the upstream server- Returns:
- the upstream response
- Throws:
IllegalArgumentException- if the request is null or the server rejects the request
-
scenario
Obtain a typed handle for inspecting and driving a stateful scenario by name. The handle wraps the/mockserver/scenario/{name}control-plane endpoints.- Parameters:
name- the scenario name- Returns:
- a handle for the named scenario
-
scenarios
List every known scenario and its current state.- Returns:
- the list of scenarios, empty if none are known
-