Class Expectation


public class Expectation extends ObjectWithJsonToString
Author:
jamesdbloom
  • Field Details

    • FORCE_RESPONSE_INDEX_HEADER

      public static final String FORCE_RESPONSE_INDEX_HEADER
      Request header (0-based) that lets a caller force which entry of a multi-response httpResponses sequence is served for that single request — overriding the configured ResponseMode without advancing the rotation position (peek semantics; see getPrimaryAction(Integer) and consumeMatch(Integer)). Invalid or out-of-bounds values are ignored (normal selection applies). The header is NOT stripped from the request model: it is retained in recordings and on the logged request, and matching is unaffected. It is filtered only from outbound forwards — HTTP/proxy forwards via MockServerHttpRequestToFullHttpRequest.setHeader and the WebSocket passthrough via WebSocketProxyRelayHandler.isSuppressedRelayHeader — so it never leaks upstream.
      See Also:
  • Constructor Details

  • Method Details

    • when

      public static Expectation when(String specUrlOrPayload, String operationId)
      Specify the OpenAPI and operationId to match against by URL or payload and string as follows:

         // Create from a publicly hosted HTTP location (json or yaml)
         when("https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore-expanded.yaml", "showPetById")
      
         // Create from a file on the local filesystem (json or yaml)
         when("file://Users/myuser/git/mockserver/mockserver-core/src/test/resources/org/mockserver/openapi/openapi_petstore_example.json", "showPetById");
      
         // Create from a classpath resource in the /api package (json or yaml)
         when("org/mockserver/openapi/openapi_petstore_example.json", "showPetById");
      
         // Create from an OpenAPI payload (json or yaml)
         when("{\"openapi\": \"3.0.0\", \"info\": { ...", "showPetById")
       

      Parameters:
      specUrlOrPayload - the OpenAPI to match against by URL or payload
      operationId - operationId from the OpenAPI to match against i.e. "showPetById"
      Returns:
      the Expectation
    • when

      public static Expectation when(String specUrlOrPayload, String operationId, int priority)
      Specify the OpenAPI and operationId to match against by URL or payload and string with a match priority as follows:

         // Create from a publicly hosted HTTP location (json or yaml)
         when("https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore-expanded.yaml", "showPetById", 10)
      
         // Create from a file on the local filesystem (json or yaml)
         when("file://Users/myuser/git/mockserver/mockserver-core/src/test/resources/org/mockserver/openapi/openapi_petstore_example.json", "showPetById", 10);
      
         // Create from a classpath resource in the /api package (json or yaml)
         when("org/mockserver/openapi/openapi_petstore_example.json", "showPetById", 10);
      
         // Create from an OpenAPI payload (json or yaml)
         when("{\"openapi\": \"3.0.0\", \"info\": { ...", "showPetById", 10)
       

      Parameters:
      specUrlOrPayload - the OpenAPI to match against by URL or payload
      operationId - operationId from the OpenAPI to match against i.e. "showPetById"
      priority - the priority with which this expectation is used to match requests compared to other expectations (high first)
      Returns:
      the Expectation
    • when

      public static Expectation when(String specUrlOrPayload, String operationId, Times times, TimeToLive timeToLive)
      Specify the OpenAPI and operationId to match against by URL or payload and string for a limit number of times or time as follows:

         // Create from a publicly hosted HTTP location (json or yaml)
         when("https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore-expanded.yaml", "showPetById", 5, exactly(TimeUnit.SECONDS, 90))
      
         // Create from a file on the local filesystem (json or yaml)
         when("file://Users/myuser/git/mockserver/mockserver-core/src/test/resources/org/mockserver/openapi/openapi_petstore_example.json", "showPetById", 5, exactly(TimeUnit.SECONDS, 90));
      
         // Create from a classpath resource in the /api package (json or yaml)
         when("org/mockserver/openapi/openapi_petstore_example.json", "showPetById", 5, exactly(TimeUnit.SECONDS, 90));
      
         // Create from an OpenAPI payload (json or yaml)
         when("{\"openapi\": \"3.0.0\", \"info\": { ...", "showPetById", 5, exactly(TimeUnit.SECONDS, 90))
       

      Parameters:
      specUrlOrPayload - the OpenAPI to match against by URL or payload
      operationId - operationId from the OpenAPI to match against i.e. "showPetById"
      times - the number of times to use this expectation to match requests
      timeToLive - the time this expectation should be used to match requests
      Returns:
      the Expectation
    • when

      public static Expectation when(String specUrlOrPayload, String operationId, Times times, TimeToLive timeToLive, int priority)
      Specify the OpenAPI and operationId to match against by URL or payload and string for a limit number of times or time and a match priority as follows:

         // Create from a publicly hosted HTTP location (json or yaml)
         when("https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore-expanded.yaml", "showPetById", 5, exactly(TimeUnit.SECONDS, 90))
      
         // Create from a file on the local filesystem (json or yaml)
         when("file://Users/myuser/git/mockserver/mockserver-core/src/test/resources/org/mockserver/openapi/openapi_petstore_example.json", "showPetById", 5, exactly(TimeUnit.SECONDS, 90));
      
         // Create from a classpath resource in the /api package (json or yaml)
         when("org/mockserver/openapi/openapi_petstore_example.json", "showPetById", 5, exactly(TimeUnit.SECONDS, 90));
      
         // Create from an OpenAPI payload (json or yaml)
         when("{\"openapi\": \"3.0.0\", \"info\": { ...", "showPetById", 5, exactly(TimeUnit.SECONDS, 90))
       

      Parameters:
      specUrlOrPayload - the OpenAPI to match against by URL or payload
      operationId - operationId from the OpenAPI to match against i.e. "showPetById"
      times - the number of times to use this expectation to match requests
      timeToLive - the time this expectation should be used to match requests
      priority - the priority with which this expectation is used to match requests compared to other expectations (high first)
      Returns:
      the Expectation
    • when

      public static Expectation when(HttpRequest httpRequest)
      Specify the HttpRequest to match against as follows:

           when(
               request()
                   .withMethod("GET")
                   .withPath("/some/path")
           ).thenRespond(
               response()
                   .withContentType(APPLICATION_JSON_UTF_8)
                   .withBody("{\"some\": \"body\"}")
           );
       

      Parameters:
      httpRequest - the HttpRequest to match against
      Returns:
      the Expectation
    • when

      public static Expectation when(HttpRequest httpRequest, int priority)
      Specify the HttpRequest to match against with a match priority as follows:

           when(
               request()
                   .withMethod("GET")
                   .withPath("/some/path"),
               10
           ).thenRespond(
               response()
                   .withContentType(APPLICATION_JSON_UTF_8)
                   .withBody("{\"some\": \"body\"}")
           );
       

      Parameters:
      httpRequest - the HttpRequest to match against
      priority - the priority with which this expectation is used to match requests compared to other expectations (high first)
      Returns:
      the Expectation
    • when

      public static Expectation when(HttpRequest httpRequest, Times times, TimeToLive timeToLive)
      Specify the HttpRequest to match against for a limit number of times or time as follows:

           when(
               request()
                   .withMethod("GET")
                   .withPath("/some/path"),
               5,
               exactly(TimeUnit.SECONDS, 90)
           ).thenRespond(
               response()
                   .withContentType(APPLICATION_JSON_UTF_8)
                   .withBody("{\"some\": \"body\"}")
           );
       

      Parameters:
      httpRequest - the HttpRequest to match against
      times - the number of times to use this expectation to match requests
      timeToLive - the time this expectation should be used to match requests
      Returns:
      the Expectation
    • when

      public static Expectation when(HttpRequest httpRequest, Times times, TimeToLive timeToLive, int priority)
      Specify the HttpRequest to match against for a limit number of times or time and a match priority as follows:

           when(
               request()
                   .withMethod("GET")
                   .withPath("/some/path"),
               5,
               exactly(TimeUnit.SECONDS, 90),
               10
           ).thenRespond(
               response()
                   .withContentType(APPLICATION_JSON_UTF_8)
                   .withBody("{\"some\": \"body\"}")
           );
       

      Parameters:
      httpRequest - the HttpRequest to match against
      times - the number of times to use this expectation to match requests
      timeToLive - the time this expectation should be used to match requests
      priority - the priority with which this expectation is used to match requests compared to other expectations (high first)
      Returns:
      the Expectation
    • withId

      public Expectation withId(String id)

      Set id of this expectation which can be used to update this expectation later or for clearing or verifying by expectation id.

      Note: Each unique expectation must have a unique id otherwise this expectation will update a existing expectation with the same id.

      Parameters:
      id - unique string for expectation's id
    • withIdIfNull

      public Expectation withIdIfNull(String id)
    • getId

      public String getId()
    • withPriority

      public Expectation withPriority(int priority)

      Set priority of this expectation which is used to determine the matching order of expectations when a request is received.

      Matching is ordered by priority (highest first) then creation (earliest first).

      Parameters:
      priority - expectation's priority
    • getPriority

      public int getPriority()
    • withPercentage

      public Expectation withPercentage(Integer percentage)
    • getPercentage

      public Integer getPercentage()
    • withChaos

      public Expectation withChaos(HttpChaosProfile chaos)
    • getChaos

      public HttpChaosProfile getChaos()
    • withRateLimit

      public Expectation withRateLimit(RateLimit rateLimit)
    • getRateLimit

      public RateLimit getRateLimit()
    • matchesByPercentage

      public boolean matchesByPercentage()
    • withCreated

      public Expectation withCreated(long created)
    • getCreated

      public long getCreated()
    • getSortableId

      public SortableExpectationId getSortableId()
    • getHttpRequest

      public RequestDefinition getHttpRequest()
    • getHttpResponse

      public HttpResponse getHttpResponse()
    • getHttpResponseTemplate

      public HttpTemplate getHttpResponseTemplate()
    • getHttpResponseClassCallback

      public HttpClassCallback getHttpResponseClassCallback()
    • getHttpResponseObjectCallback

      public HttpObjectCallback getHttpResponseObjectCallback()
    • getHttpForward

      public HttpForward getHttpForward()
    • getHttpForwardTemplate

      public HttpTemplate getHttpForwardTemplate()
    • getHttpForwardClassCallback

      public HttpClassCallback getHttpForwardClassCallback()
    • getHttpForwardObjectCallback

      public HttpObjectCallback getHttpForwardObjectCallback()
    • getHttpOverrideForwardedRequest

      public HttpOverrideForwardedRequest getHttpOverrideForwardedRequest()
    • getHttpForwardValidateAction

      public HttpForwardValidateAction getHttpForwardValidateAction()
    • getHttpForwardWithFallback

      public HttpForwardWithFallback getHttpForwardWithFallback()
    • getHttpSseResponse

      public HttpSseResponse getHttpSseResponse()
    • getHttpLlmResponse

      public HttpLlmResponse getHttpLlmResponse()
    • getHttpWebSocketResponse

      public HttpWebSocketResponse getHttpWebSocketResponse()
    • getGrpcStreamResponse

      public GrpcStreamResponse getGrpcStreamResponse()
    • getGrpcBidiResponse

      public GrpcBidiResponse getGrpcBidiResponse()
    • getBinaryResponse

      public BinaryResponse getBinaryResponse()
    • getDnsResponse

      public DnsResponse getDnsResponse()
    • getHttpError

      public HttpError getHttpError()
    • getBeforeActions

      public List<AfterAction> getBeforeActions()
    • getAfterActions

      public List<AfterAction> getAfterActions()
    • getSteps

      public List<ExpectationStep> getSteps()
    • withSteps

      public Expectation withSteps(ExpectationStep... steps)
    • withSteps

      public Expectation withSteps(List<ExpectationStep> steps)
    • validateSteps

      public String validateSteps()
      Validates the steps list for legal combinations:
      • Exactly one step must be marked as the responder (responder = true).
      • httpError cannot be combined with other steps (it must be the only step).
      • Each step must have exactly one action target set.
      • steps cannot be combined with beforeActions — use steps for the full ordered pipeline.
      • steps cannot be combined with a top-level primary response action — the responder step defines the action.
      • steps MAY coexist with afterActions — after-actions fire after the steps pipeline completes.
      Returns:
      null if valid, or an error message describing the violation
    • getHttpResponses

      public List<HttpResponse> getHttpResponses()
    • thenRespond

      public Expectation thenRespond(List<HttpResponse> httpResponses)
    • getResponseMode

      public ResponseMode getResponseMode()
    • withResponseMode

      public Expectation withResponseMode(ResponseMode responseMode)
    • getResponseWeights

      public List<Integer> getResponseWeights()
    • withResponseWeights

      public Expectation withResponseWeights(List<Integer> responseWeights)
      Specify the relative weight of each response in httpResponses (index-aligned), used when ResponseMode.WEIGHTED selection is active. A missing or null weight defaults to 1. Weights are ignored unless the response mode is WEIGHTED.
    • getSwitchAfter

      public Integer getSwitchAfter()
    • withSwitchAfter

      public Expectation withSwitchAfter(Integer switchAfter)
      Lightweight per-expectation hit-count branching, used when ResponseMode.SWITCH selection is active.

      With an index-aligned httpResponses list and a positive switchAfter of N, the expectation serves the first response for its first N matches, then advances one index for every further block of N matches, clamping at the last response. The common case — a list of two responses — therefore serves the first response for N calls and the second response for every call after that, letting a single expectation "respond differently after the Nth call" without a full scenario. A null or non-positive switchAfter (or a response mode other than SWITCH) leaves behaviour unchanged.

      Parameters:
      switchAfter - the number of matches served by each response before advancing to the next (must be >= 1)
    • withBeforeActions

      public Expectation withBeforeActions(AfterAction... beforeActions)
    • withBeforeActions

      public Expectation withBeforeActions(List<AfterAction> beforeActions)
    • withAfterActions

      public Expectation withAfterActions(AfterAction... afterActions)
    • withAfterActions

      public Expectation withAfterActions(List<AfterAction> afterActions)
    • withNamespace

      public Expectation withNamespace(String namespace)

      Set the optional namespace (a.k.a. tenant) that this expectation belongs to, enabling multiple teams or test-suites to share a single MockServer instance without their expectations colliding.

      A null namespace (the default) places the expectation in the global namespace, which is matched regardless of any request namespace. A non-null namespace scopes the expectation so it only matches requests that carry the configured namespace header (matchNamespaceHeader, default X-MockServer-Namespace) with this exact value.

      The value is normalised at the source: a null, empty or whitespace-only namespace is stored as null (global), so a blank namespace is unambiguously "global" and can never produce an expectation that matches everything yet cannot be cleared by namespace.

      Parameters:
      namespace - the namespace (tenant) for this expectation, or null for global
    • getNamespace

      public String getNamespace()
    • withScenarioName

      public Expectation withScenarioName(String scenarioName)
    • getScenarioName

      public String getScenarioName()
    • withScenarioState

      public Expectation withScenarioState(String scenarioState)
    • getScenarioState

      public String getScenarioState()
    • withNewScenarioState

      public Expectation withNewScenarioState(String newScenarioState)
    • getNewScenarioState

      public String getNewScenarioState()
    • getCapture

      public List<CaptureRule> getCapture()
    • withCapture

      public Expectation withCapture(List<CaptureRule> capture)
    • withCapture

      public Expectation withCapture(CaptureRule... capture)
    • getCrossProtocolScenarios

      public List<CrossProtocolScenario> getCrossProtocolScenarios()
    • withCrossProtocolScenario

      public Expectation withCrossProtocolScenario(CrossProtocolScenario scenario)
    • withCrossProtocolScenarios

      public Expectation withCrossProtocolScenarios(List<CrossProtocolScenario> scenarios)
    • getAction

      public Action getAction()
    • getPrimaryAction

      public Action getPrimaryAction()
    • isForcedResponseServe

      public boolean isForcedResponseServe(Integer forcedResponseIndex)
      Whether a forcedResponseIndex would actually be served as a forced variant by getPrimaryAction(Integer) — i.e. it is non-null, in-bounds, and this expectation carries a multi-response httpResponses sequence with no steps. This is the single source of truth for "is this a forced serve", used both at match time (to decide whether the request advances the rotation counter) and at resolution time (to pick the variant), so the two decisions can never diverge.
    • getPrimaryAction

      public Action getPrimaryAction(Integer forcedResponseIndex)
      Action-resolution overload that honours a caller-forced response-sequence index (the FORCE_RESPONSE_INDEX_HEADER affordance). When the index would be served, the response at that exact index is returned without reading or advancing the rotation position (peek semantics), overriding the configured ResponseMode. A null, out-of-bounds, or otherwise inapplicable index falls through to the normal getPrimaryAction() selection — a forced index is never an error. The rotation is left undisturbed structurally: a forced request never increments rotationCount (see consumeMatch(Integer)), so no resolution-time compensation is needed here.
      Parameters:
      forcedResponseIndex - the 0-based sequence index to force, or null for normal selection
    • getAction

      public Action getAction(Integer forcedResponseIndex)
      Convenience alias of getPrimaryAction(Integer) mirroring the no-arg getAction().
    • parseForcedResponseIndex

      public static Integer parseForcedResponseIndex(RequestDefinition request)
      Parses the 0-based force-response-variant index from the FORCE_RESPONSE_INDEX_HEADER header on an incoming request. Returns null when the request is null/not an HTTP request, the header is absent/blank, or the value is not an integer — in every such case normal response selection applies (the header is advisory and never an error). Bounds are validated later against the matched expectation's httpResponses in isForcedResponseServe(java.lang.Integer).
    • getPreResponderSteps

      public List<ExpectationStep> getPreResponderSteps()
      Returns the ordered list of side-effect steps (non-responder steps that appear before the responder in the steps list). Returns empty list when steps is null or empty, or when no non-responder steps precede the responder.
    • getPostResponderSteps

      public List<ExpectationStep> getPostResponderSteps()
      Returns the ordered list of side-effect steps that appear after the responder in the steps list (post-responder side-effects).
    • getSecondaryActions

      public List<Action> getSecondaryActions()
    • getTimes

      public Times getTimes()
    • getTimeToLive

      public TimeToLive getTimeToLive()
    • thenRespond

      public Expectation thenRespond(HttpResponse httpResponse)
    • thenRespond

      public Expectation thenRespond(HttpTemplate httpTemplate)
    • thenRespond

      public Expectation thenRespond(HttpClassCallback httpClassCallback)
    • thenRespond

      public Expectation thenRespond(HttpObjectCallback httpObjectCallback)
    • thenForward

      public Expectation thenForward(HttpForward httpForward)
    • thenForward

      public Expectation thenForward(HttpTemplate httpTemplate)
    • thenForward

      public Expectation thenForward(HttpClassCallback httpClassCallback)
    • thenForward

      public Expectation thenForward(HttpObjectCallback httpObjectCallback)
    • thenForward

      public Expectation thenForward(HttpOverrideForwardedRequest httpOverrideForwardedRequest)
    • thenForwardValidate

      public Expectation thenForwardValidate(HttpForwardValidateAction httpForwardValidateAction)
    • thenForwardWithFallback

      public Expectation thenForwardWithFallback(HttpForwardWithFallback httpForwardWithFallback)
    • thenRespondWithSse

      public Expectation thenRespondWithSse(HttpSseResponse httpSseResponse)
    • thenRespondWithLlm

      public Expectation thenRespondWithLlm(HttpLlmResponse httpLlmResponse)
    • thenRespondWithWebSocket

      public Expectation thenRespondWithWebSocket(HttpWebSocketResponse httpWebSocketResponse)
    • thenRespondWithGrpcStream

      public Expectation thenRespondWithGrpcStream(GrpcStreamResponse grpcStreamResponse)
    • thenRespondWithGrpcBidi

      public Expectation thenRespondWithGrpcBidi(GrpcBidiResponse grpcBidiResponse)
    • thenRespondWithBinary

      public Expectation thenRespondWithBinary(BinaryResponse binaryResponse)
    • thenRespondWithDns

      public Expectation thenRespondWithDns(DnsResponse dnsResponse)
    • thenError

      public Expectation thenError(HttpError httpError)
    • isActive

      public boolean isActive()
    • decrementRemainingMatches

      public boolean decrementRemainingMatches()
    • consumeMatch

      public boolean consumeMatch()
    • consumeMatch

      public boolean consumeMatch(Integer forcedResponseIndex)
      Records a match, advancing the response-sequence rotation only for a NORMAL request. A request served a forced variant (isForcedResponseServe(Integer) for forcedResponseIndex is true) still decrements Times and increments matchCount, but does NOT advance rotationCount — so it is transparent to the rotation seen by concurrent normal callers (peek semantics). forcedResponseIndex is null for a normal request.
    • consumeMatchLocally

      public void consumeMatchLocally()
    • consumeMatchLocally

      public void consumeMatchLocally(Integer forcedResponseIndex)
      Records a match consumption WITHOUT decrementing the node-local Times counter. Used when a clustered backend has already atomically decremented the shared remaining-times counter via CAS — the local Times object must not also decrement, or the node-local counter would diverge from the shared one.

      Updates matchCount, the rotation snapshot, and chaosFirstMatchEpochMillis exactly as consumeMatch(Integer) does (including the forced-request rotation-transparency rule). These are node-local runtime metrics that do not need to be shared across the cluster.

    • getMatchCount

      public int getMatchCount()
    • getChaosFirstMatchEpochMillis

      public long getChaosFirstMatchEpochMillis()
      Epoch-ms (from the controllable clock) of this expectation's first match, or 0 if it has not been matched yet. Anchors any time-based chaos outage window. Transient runtime state — not serialized, not cloned.
    • contains

      public boolean contains(HttpRequest httpRequest)
    • clone

      public Expectation clone()
      Overrides:
      clone in class Object
    • fieldsExcludedFromEqualsAndHashCode

      public String[] fieldsExcludedFromEqualsAndHashCode()
      Overrides:
      fieldsExcludedFromEqualsAndHashCode in class ObjectWithReflectiveEqualsHashCodeToString
    • equals

      public boolean equals(Object o)
      Overrides:
      equals in class ObjectWithReflectiveEqualsHashCodeToString
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class ObjectWithReflectiveEqualsHashCodeToString