Class MockServerClient

java.lang.Object
org.mockserver.client.MockServerClient
All Implemented Interfaces:
Closeable, AutoCloseable, Stoppable
Direct Known Subclasses:
ClientAndServer

public class MockServerClient extends Object implements Stoppable
Author:
jamesdbloom
  • Field Details

  • Constructor Details

    • MockServerClient

      public MockServerClient(Configuration configuration, CompletableFuture<Integer> portFuture)
      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

      public MockServerClient(ClientConfiguration configuration, CompletableFuture<Integer> portFuture)
      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

      public MockServerClient(String host, int port)
      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 with
      port - the port for the MockServer to communicate with
    • MockServerClient

      public MockServerClient(Configuration configuration, String host, int port)
      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 with
      port - the port for the MockServer to communicate with
    • MockServerClient

      public MockServerClient(ClientConfiguration configuration, String host, int port)
      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 with
      port - the port for the MockServer to communicate with
    • MockServerClient

      public 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 mockServerClient = new MockServerClient("localhost", 1080, "/mockserver");

      Parameters:
      host - the host for the MockServer to communicate with
      port - the port for the MockServer to communicate with
      contextPath - the context path that the MockServer war is deployed to
    • MockServerClient

      public 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 mockServerClient = new MockServerClient("localhost", 1080, "/mockserver");

      Parameters:
      host - the host for the MockServer to communicate with
      port - the port for the MockServer to communicate with
      contextPath - 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 with
      port - the port for the MockServer to communicate with
      contextPath - the context path that the MockServer war is deployed to
  • Method Details

    • setProxyConfiguration

      @Deprecated public MockServerClient setProxyConfiguration(ProxyConfiguration proxyConfiguration)
      Deprecated.
      use withProxyConfiguration which is more consistent with MockServer API style
    • withProxyConfiguration

      public MockServerClient withProxyConfiguration(ProxyConfiguration proxyConfiguration)
      Configure communication to MockServer to go via a proxy
    • withControlPlaneJWT

      public MockServerClient withControlPlaneJWT(String controlPlaneJWT)
      Specify JWT to use for control plane authorisation
    • withControlPlaneJWT

      public MockServerClient withControlPlaneJWT(Supplier<String> controlPlaneJWTSupplier)
      Specify JWT supplier to use for control plane authorisation
    • setRequestOverride

      @Deprecated public MockServerClient setRequestOverride(HttpRequest requestOverride)
      Deprecated.
      use withRequestOverride which is more consistent with MockServer API style
    • withRequestOverride

      public MockServerClient withRequestOverride(HttpRequest requestOverride)
    • isSecure

      public boolean isSecure()
    • withSecure

      public MockServerClient withSecure(boolean secure)
    • remoteAddress

      public InetSocketAddress remoteAddress()
    • contextPath

      public String contextPath()
    • getPort

      public Integer getPort()
    • openUI

      public MockServerClient 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

      public MockServerClient openUI(TimeUnit timeUnit, long pause)
      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.SECONDS
      pause - the number of time units to delay before the function returns to ensure the UI is receiving logs
    • isRunning

      @Deprecated public boolean isRunning()
      Deprecated.
      use hasStopped() or hasStarted() instead
      Returns 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 public boolean isRunning(int attempts, long timeout, TimeUnit timeUnit)
      Deprecated.
      use hasStopped() or hasStarted() instead
      Returns 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

      public boolean hasStopped(int attempts, long timeout, TimeUnit timeUnit)
      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

      public boolean hasStarted(int attempts, long timeout, TimeUnit timeUnit)
      Returns whether server MockServer has started, by polling the MockServer a configurable amount of times
    • bind

      public List<Integer> bind(Integer... ports)
      Bind new ports to listen on
    • stopAsync

      public Future<MockServerClient> 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)
      Specified by:
      stop in interface Stoppable
    • stop

      public CompletableFuture<MockServerClient> stop(boolean ignoreFailure)
      Stop MockServer gracefully (only support for Netty version, not supported for WAR version)
    • close

      public void close()
      Specified by:
      close in interface AutoCloseable
      Specified by:
      close in interface Closeable
    • reset

      public MockServerClient reset()
      Reset MockServer by clearing all expectations
    • clear

      public MockServerClient clear(RequestDefinition requestDefinition)
      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

      public MockServerClient clear(String expectationId)
      Clear all expectations and logs that match the expectation id
      Parameters:
      expectationId - the expectation id that is used to clear expectations and logs
    • clear

      public MockServerClient clear(ExpectationId expectationId)
      Clear all expectations and logs that match the expectation id
      Parameters:
      expectationId - the expectation id that is used to clear expectations and logs
    • clear

      public MockServerClient clear(RequestDefinition requestDefinition, ClearType type)
      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 cleared
      type - the type to clear, EXPECTATION, LOG or BOTH
    • clear

      public MockServerClient clear(String expectationId, ClearType type)
      Clear expectations, logs or both that match the expectation id
      Parameters:
      expectationId - the expectation id that is used to clear expectations and logs
      type - the type to clear, EXPECTATION, LOG or BOTH
    • clear

      public MockServerClient clear(ExpectationId expectationId, ClearType type)
      Clear expectations, logs or both that match the expectation id
      Parameters:
      expectationId - the expectation id that is used to clear expectations and logs
      type - the type to clear, EXPECTATION, LOG or BOTH
    • verify

      public MockServerClient verify(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:
      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 fails
      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(String... 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:
      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(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:
      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 fails
      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(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 pass
      times - 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 pass
      times - the number of times this request must be matched
      maximumNumberOfRequestToReturnInVerificationFailure - the maximum number requests return in the error response when the verification fails
      Throws:
      AssertionError - if the request has not been found
    • verify

      public MockServerClient verify(String 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 pass
      times - 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 pass
      times - 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 pass
      times - the number of times this request must be matched
      maximumNumberOfRequestToReturnInVerificationFailure - the maximum number requests return in the error response when the verification fails
      Throws:
      AssertionError - if the request has not been found
    • verifyZeroInteractions

      public MockServerClient verifyZeroInteractions() throws AssertionError
      Verify no requests have been sent.
      Throws:
      AssertionError - if any request has been found
    • retrieveRecordedRequests

      public HttpRequest[] retrieveRecordedRequests(RequestDefinition requestDefinition)
      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

      public String retrieveRecordedRequests(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 requests
      format - 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 requests
      format - 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

      public Expectation[] 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 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

      public String retrieveRecordedExpectations(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 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
      format - 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

      public String retrieveLogMessages(RequestDefinition requestDefinition)
      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

      public String[] retrieveLogMessagesArray(RequestDefinition requestDefinition)
      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

      public LogEntry[] retrieveLogEntries(RequestDefinition requestDefinition)
      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

      public LogEntry[] retrieveLogEntriesByCorrelationId(String correlationId)
      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 all
      fromEpochMillis - start of time window (inclusive), milliseconds since epoch
      toEpochMillis - end of time window (exclusive), milliseconds since epoch
      Returns:
      an array of log entries within the specified time window
    • when

      public ForwardChainExpectation when(RequestDefinition requestDefinition)
      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

      public ForwardChainExpectation when(RequestDefinition requestDefinition, Times times)
      Specify a limited expectation that will respond a specified number of times when the http is matched

      Example 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 respond
      times - 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 matched

      Example 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 respond
      times - the number of times to respond when this http is matched
      timeToLive - 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 respond
      times - the number of times to respond when this http is matched
      timeToLive - the length of time from when the server receives the expectation that the expectation should be active
      priority - 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

      public Expectation[] upsert(OpenAPIExpectation... openAPIExpectations)
      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

      public Expectation[] upsert(Expectation... expectations)
      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

      public MockServerClient crud(CrudExpectationsDefinition crudDefinition)
      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 public Expectation[] sendExpectation(Expectation... expectations)
      Deprecated.
      this is deprecated due to unclear naming, use method upsert(Expectation... expectations) instead
      Specify 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

      public Expectation[] retrieveActiveExpectations(RequestDefinition requestDefinition)
      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 String retrieveActiveExpectations(RequestDefinition requestDefinition, Format format)
      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
      format - 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

      public String debugMismatch(RequestDefinition requestDefinition)
      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

      public String retrieveLogsByCorrelationId(String correlationId)
      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

      public String retrieveMetrics()
    • retrieveConfiguration

      public String retrieveConfiguration()
    • updateConfiguration

      public String updateConfiguration(String configurationJson)
    • uploadGrpcDescriptor

      public MockServerClient uploadGrpcDescriptor(byte[] descriptorSetBytes)
    • retrieveGrpcServices

      public String retrieveGrpcServices()
    • clearGrpcDescriptors

      public MockServerClient clearGrpcDescriptors()
    • freezeClock

      public MockServerClient freezeClock(Instant instant)
      Freeze the MockServer clock at the specified instant.
      Parameters:
      instant - the instant to freeze the clock at
      Returns:
      this MockServerClient
    • freezeClock

      public MockServerClient freezeClock()
      Freeze the MockServer clock at the current time.
      Returns:
      this MockServerClient
    • advanceClock

      public MockServerClient advanceClock(Duration duration)
      Advance the MockServer clock by the specified duration.
      Parameters:
      duration - the duration to advance the clock by
      Returns:
      this MockServerClient
    • resetClock

      public MockServerClient resetClock()
      Reset the MockServer clock to real wall-clock time.
      Returns:
      this MockServerClient
    • clockStatus

      public String 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

      public MockServerClient setServiceChaos(String host, HttpChaosProfile chaos)
      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 own chaos block (an expectation's own chaos always wins). The host is matched case-insensitively, ignoring any :port. See PUT /mockserver/serviceChaos.
      Parameters:
      host - the upstream host to break
      chaos - the chaos profile to apply to that host's forwarded responses
      Returns:
      this MockServerClient
    • setServiceChaos

      public MockServerClient setServiceChaos(String host, HttpChaosProfile chaos, long ttlMillis)
      Register a service-scoped HTTP chaos profile for an upstream host that auto-reverts after ttlMillis milliseconds (a "dead-man's switch" so the chaos self-heals even if removeServiceChaos(String) / clearServiceChaos() is never called). See PUT /mockserver/serviceChaos.
      Parameters:
      host - the upstream host to break
      chaos - the chaos profile to apply to that host's forwarded responses
      ttlMillis - milliseconds after which the chaos auto-reverts; <= 0 means no expiry
      Returns:
      this MockServerClient
    • removeServiceChaos

      public MockServerClient removeServiceChaos(String host)
      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

      public MockServerClient clearServiceChaos()
      Clear all service-scoped chaos profiles.
      Returns:
      this MockServerClient
    • serviceChaosStatus

      public String 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

      public String loadAsyncApi(String specOrWrappedJson)
      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

      public String 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

      public MockServerClient verifyAsyncMessage(String verificationJson) throws AssertionError
      Verify async messages recorded by subscribers against the given criteria. The verification JSON must contain at least a channel field, and optionally payloadSubstring, payloadJsonPath, expectedValue, and count (with atLeast, atMost, or exactly).
      Parameters:
      verificationJson - the verification criteria as JSON
      Throws:
      AssertionError - if the verification fails (server responds with 406)