Class Expectation
- Author:
- jamesdbloom
-
Constructor Summary
ConstructorsConstructorDescriptionExpectation(RequestDefinition requestDefinition) Expectation(RequestDefinition requestDefinition, Times times, TimeToLive timeToLive, int priority) -
Method Summary
Modifier and TypeMethodDescriptionclone()booleanvoidRecords a match consumption WITHOUT decrementing the node-local Times counter.booleancontains(HttpRequest httpRequest) booleanbooleanString[]getChaos()longEpoch-ms (from the controllable clock) of this expectation's first match, or0if it has not been matched yet.longgetId()intReturns the ordered list of side-effect steps that appear after the responder in the steps list (post-responder side-effects).Returns the ordered list of side-effect steps (non-responder steps that appear before the responder in the steps list).intgetSteps()getTimes()inthashCode()booleanisActive()booleanthenForward(HttpClassCallback httpClassCallback) thenForward(HttpForward httpForward) thenForward(HttpObjectCallback httpObjectCallback) thenForward(HttpOverrideForwardedRequest httpOverrideForwardedRequest) thenForward(HttpTemplate httpTemplate) thenForwardValidate(HttpForwardValidateAction httpForwardValidateAction) thenForwardWithFallback(HttpForwardWithFallback httpForwardWithFallback) thenRespond(List<HttpResponse> httpResponses) thenRespond(HttpClassCallback httpClassCallback) thenRespond(HttpObjectCallback httpObjectCallback) thenRespond(HttpResponse httpResponse) thenRespond(HttpTemplate httpTemplate) thenRespondWithBinary(BinaryResponse binaryResponse) thenRespondWithDns(DnsResponse dnsResponse) thenRespondWithGrpcBidi(GrpcBidiResponse grpcBidiResponse) thenRespondWithGrpcStream(GrpcStreamResponse grpcStreamResponse) thenRespondWithLlm(HttpLlmResponse httpLlmResponse) thenRespondWithSse(HttpSseResponse httpSseResponse) thenRespondWithWebSocket(HttpWebSocketResponse httpWebSocketResponse) Validates the steps list for legal combinations: Exactly one step must be marked as the responder (responder = true).httpErrorcannot be combined with other steps (it must be the only step). Each step must have exactly one action target set.stepscannot be combined withbeforeActions— use steps for the full ordered pipeline.stepscannot be combined with a top-level primary response action — the responder step defines the action.stepsMAY coexist withafterActions— after-actions fire after the steps pipeline completes.static ExpectationSpecify the OpenAPI and operationId to match against by URL or payload and string as follows:static ExpectationSpecify the OpenAPI and operationId to match against by URL or payload and string with a match priority as follows:static Expectationwhen(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:static Expectationwhen(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:static Expectationwhen(HttpRequest httpRequest) Specify the HttpRequest to match against as follows:static Expectationwhen(HttpRequest httpRequest, int priority) Specify the HttpRequest to match against with a match priority as follows:static Expectationwhen(HttpRequest httpRequest, Times times, TimeToLive timeToLive) Specify the HttpRequest to match against for a limit number of times or time as follows:static Expectationwhen(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:withAfterActions(List<AfterAction> afterActions) withAfterActions(AfterAction... afterActions) withBeforeActions(List<AfterAction> beforeActions) withBeforeActions(AfterAction... beforeActions) withCapture(List<CaptureRule> capture) withCapture(CaptureRule... capture) withChaos(HttpChaosProfile chaos) withCreated(long created) withCrossProtocolScenarios(List<CrossProtocolScenario> scenarios) Set id of this expectation which can be used to update this expectation later or for clearing or verifying by expectation id.withIdIfNull(String id) 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.withNewScenarioState(String newScenarioState) withPercentage(Integer percentage) withPriority(int priority) Set priority of this expectation which is used to determine the matching order of expectations when a request is received.withRateLimit(RateLimit rateLimit) withResponseMode(ResponseMode responseMode) withResponseWeights(List<Integer> responseWeights) Specify the relative weight of each response inhttpResponses(index-aligned), used whenResponseMode.WEIGHTEDselection is active.withScenarioName(String scenarioName) withScenarioState(String scenarioState) withSteps(List<ExpectationStep> steps) withSteps(ExpectationStep... steps) withSwitchAfter(Integer switchAfter) Lightweight per-expectation hit-count branching, used whenResponseMode.SWITCHselection is active.Methods inherited from class org.mockserver.model.ObjectWithJsonToString
toString
-
Constructor Details
-
Expectation
-
Expectation
public Expectation(RequestDefinition requestDefinition, Times times, TimeToLive timeToLive, int priority)
-
-
Method Details
-
when
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 payloadoperationId- operationId from the OpenAPI to match against i.e. "showPetById"- Returns:
- the Expectation
-
when
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 payloadoperationId- 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 payloadoperationId- operationId from the OpenAPI to match against i.e. "showPetById"times- the number of times to use this expectation to match requeststimeToLive- 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 payloadoperationId- operationId from the OpenAPI to match against i.e. "showPetById"times- the number of times to use this expectation to match requeststimeToLive- the time this expectation should be used to match requestspriority- the priority with which this expectation is used to match requests compared to other expectations (high first)- Returns:
- the Expectation
-
when
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
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 againstpriority- the priority with which this expectation is used to match requests compared to other expectations (high first)- Returns:
- the Expectation
-
when
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 againsttimes- the number of times to use this expectation to match requeststimeToLive- 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 againsttimes- the number of times to use this expectation to match requeststimeToLive- the time this expectation should be used to match requestspriority- the priority with which this expectation is used to match requests compared to other expectations (high first)- Returns:
- the Expectation
-
withId
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
-
getId
-
withPriority
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
-
getPercentage
-
withChaos
-
getChaos
-
withRateLimit
-
getRateLimit
-
matchesByPercentage
public boolean matchesByPercentage() -
withCreated
-
getCreated
public long getCreated() -
getSortableId
-
getHttpRequest
-
getHttpResponse
-
getHttpResponseTemplate
-
getHttpResponseClassCallback
-
getHttpResponseObjectCallback
-
getHttpForward
-
getHttpForwardTemplate
-
getHttpForwardClassCallback
-
getHttpForwardObjectCallback
-
getHttpOverrideForwardedRequest
-
getHttpForwardValidateAction
-
getHttpForwardWithFallback
-
getHttpSseResponse
-
getHttpLlmResponse
-
getHttpWebSocketResponse
-
getGrpcStreamResponse
-
getGrpcBidiResponse
-
getBinaryResponse
-
getDnsResponse
-
getHttpError
-
getBeforeActions
-
getAfterActions
-
getSteps
-
withSteps
-
withSteps
-
validateSteps
Validates the steps list for legal combinations:- Exactly one step must be marked as the responder (
responder = true). httpErrorcannot be combined with other steps (it must be the only step).- Each step must have exactly one action target set.
stepscannot be combined withbeforeActions— use steps for the full ordered pipeline.stepscannot be combined with a top-level primary response action — the responder step defines the action.stepsMAY coexist withafterActions— after-actions fire after the steps pipeline completes.
- Returns:
- null if valid, or an error message describing the violation
- Exactly one step must be marked as the responder (
-
getHttpResponses
-
thenRespond
-
getResponseMode
-
withResponseMode
-
getResponseWeights
-
withResponseWeights
Specify the relative weight of each response inhttpResponses(index-aligned), used whenResponseMode.WEIGHTEDselection is active. A missing ornullweight defaults to 1. Weights are ignored unless the response mode isWEIGHTED. -
getSwitchAfter
-
withSwitchAfter
Lightweight per-expectation hit-count branching, used whenResponseMode.SWITCHselection is active.With an index-aligned
httpResponseslist and a positiveswitchAfterofN, the expectation serves the first response for its firstNmatches, then advances one index for every further block ofNmatches, clamping at the last response. The common case — a list of two responses — therefore serves the first response forNcalls and the second response for every call after that, letting a single expectation "respond differently after the Nth call" without a full scenario. Anullor non-positiveswitchAfter(or a response mode other thanSWITCH) leaves behaviour unchanged.- Parameters:
switchAfter- the number of matches served by each response before advancing to the next (must be >= 1)
-
withBeforeActions
-
withBeforeActions
-
withAfterActions
-
withAfterActions
-
withNamespace
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
nullnamespace (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, defaultX-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
-
withScenarioName
-
getScenarioName
-
withScenarioState
-
getScenarioState
-
withNewScenarioState
-
getNewScenarioState
-
getCapture
-
withCapture
-
withCapture
-
getCrossProtocolScenarios
-
withCrossProtocolScenario
-
withCrossProtocolScenarios
-
getAction
-
getPrimaryAction
-
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
Returns the ordered list of side-effect steps that appear after the responder in the steps list (post-responder side-effects). -
getSecondaryActions
-
getTimes
-
getTimeToLive
-
thenRespond
-
thenRespond
-
thenRespond
-
thenRespond
-
thenForward
-
thenForward
-
thenForward
-
thenForward
-
thenForward
-
thenForwardValidate
-
thenForwardWithFallback
-
thenRespondWithSse
-
thenRespondWithLlm
-
thenRespondWithWebSocket
-
thenRespondWithGrpcStream
-
thenRespondWithGrpcBidi
-
thenRespondWithBinary
-
thenRespondWithDns
-
thenError
-
isActive
public boolean isActive() -
decrementRemainingMatches
public boolean decrementRemainingMatches() -
consumeMatch
public boolean consumeMatch() -
consumeMatchLocally
public void consumeMatchLocally()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, lastConsumedCount, and chaosFirstMatchEpochMillis exactly as
consumeMatch()does. 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, or0if it has not been matched yet. Anchors any time-based chaos outage window. Transient runtime state — not serialized, not cloned. -
contains
-
clone
-
fieldsExcludedFromEqualsAndHashCode
- Overrides:
fieldsExcludedFromEqualsAndHashCodein classObjectWithReflectiveEqualsHashCodeToString
-
equals
- Overrides:
equalsin classObjectWithReflectiveEqualsHashCodeToString
-
hashCode
public int hashCode()- Overrides:
hashCodein classObjectWithReflectiveEqualsHashCodeToString
-