> ## Documentation Index
> Fetch the complete documentation index at: https://moeck.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Expectations

> Define what MockServer should do when it receives a matching request.

An **expectation** tells MockServer: "when you see a request that looks like this, do that." Every expectation combines a request matcher with an action. Optionally, you can also control how many times the expectation fires, how long it stays active, and what priority it has relative to other expectations.

## Expectation structure

An expectation contains:

* **`httpRequest`** — the [request matcher](/mocking/request-matchers) that identifies which incoming requests this expectation applies to
* **action** — one of `httpResponse`, `httpForward`, `httpOverrideForwardedRequest`, `httpResponseTemplate`, `httpForwardTemplate`, `httpResponseClassCallback`, or `httpError` (see [Response Actions](/mocking/response-actions))
* **`times`** *(optional)* — how many times the expectation should fire before it is deactivated
* **`timeToLive`** *(optional)* — how long the expectation remains active
* **`priority`** *(optional)* — matching order relative to other expectations; higher values match first
* **`id`** *(optional)* — a stable identifier used to update an existing expectation

## Complete example

<CodeGroup>
  ```java Java theme={null}
  new MockServerClient("localhost", 1080)
      .when(
          request()
              .withMethod("POST")
              .withPath("/login")
              .withBody("{username: 'foo', password: 'bar'}")
      )
      .respond(
          response()
              .withStatusCode(302)
              .withCookie(
                  "sessionId", "2By8LOhBmaW5nZXJwcmludCIlMDAzMW"
              )
              .withHeader(
                  "Location", "https://www.mock-server.com"
              )
      );
  ```

  ```javascript JavaScript theme={null}
  var mockServerClient = require('mockserver-client').mockServerClient;
  mockServerClient("localhost", 1080).mockAnyResponse({
      "httpRequest": {
          "method": "POST",
          "path": "/login",
          "body": {
              "username": "foo",
              "password": "bar"
          }
      },
      "httpResponse": {
          "statusCode": 302,
          "headers": {
              "Location": [
                  "https://www.mock-server.com"
              ]
          },
          "cookies": {
              "sessionId": "2By8LOhBmaW5nZXJwcmludCIlMDAzMW"
          }
      }
  }).then(
      function () {
          console.log("expectation created");
      },
      function (error) {
          console.log(error);
      }
  );
  ```

  ```bash REST API theme={null}
  curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
      "method": "POST",
      "path": "/login",
      "body": {
        "username": "foo",
        "password": "bar"
      }
    },
    "httpResponse": {
      "statusCode": 302,
      "headers": {
        "Location": ["https://www.mock-server.com"]
      },
      "cookies": {
        "sessionId": "2By8LOhBmaW5nZXJwcmludCIlMDAzMW"
      }
    }
  }'
  ```
</CodeGroup>

## Field reference

<AccordionGroup>
  <Accordion title="times">
    Controls how many times an expectation matches before it is automatically deactivated.

    ```json theme={null}
    "times": {
      "remainingTimes": 2,
      "unlimited": false
    }
    ```

    Set `"unlimited": true` to keep the expectation active indefinitely (the default when `times` is omitted).

    In Java, use `Times.exactly(2)`, `Times.once()`, or `Times.unlimited()`.

    When you register multiple expectations with the same request matcher and different `times` values, MockServer fires them in registration order. For example, if expectation A fires three times then expectation B fires twice, requests are handled A, A, A, B, B.
  </Accordion>

  <Accordion title="timeToLive">
    Sets an expiry duration after which the expectation is automatically removed, regardless of how many remaining times it has.

    ```json theme={null}
    "timeToLive": {
      "timeUnit": "SECONDS",
      "timeToLive": 60,
      "unlimited": false
    }
    ```

    In Java, use `TimeToLive.exactly(TimeUnit.SECONDS, 60L)`.
  </Accordion>

  <Accordion title="priority">
    An integer that controls matching order. MockServer evaluates expectations from **highest priority first**, then by creation order for equal-priority expectations.

    Use a **negative** priority to create a catch-all default expectation that only matches after everything else has been tried:

    ```json theme={null}
    {
      "httpRequest": {},
      "httpResponse": { "body": "default_response" },
      "priority": -10
    }
    ```

    In Java, pass priority as the fourth argument to `.when()`:

    ```java theme={null}
    new MockServerClient("localhost", 1080)
        .when(
            request().withPath("/some/path"),
            Times.once(),
            TimeToLive.exactly(TimeUnit.SECONDS, 60L),
            10
        )
        .respond(response().withBody("some_response_body"));
    ```
  </Accordion>

  <Accordion title="id">
    A string identifier for the expectation. If you submit an expectation with an `id` that matches an existing expectation, the existing expectation is replaced entirely. MockServer assigns a UUID automatically when no `id` is provided.

    ```json theme={null}
    {
      "id": "630a6e5b-9d61-4668-a18f-a0d3df558583",
      "httpRequest": { "path": "/some/path" },
      "httpResponse": { "body": "updated_response" }
    }
    ```

    This is useful for updating a specific expectation without clearing all others.
  </Accordion>
</AccordionGroup>

## Matching order

MockServer matches active expectations in priority order, then creation order. Once a matching expectation's `times` counter reaches zero, it is deactivated. If no active expectation matches an incoming request and MockServer is not acting as a proxy, it returns a `404`.

## Next steps

<CardGroup cols={2}>
  <Card title="Request Matchers" icon="filter" href="/mocking/request-matchers">
    Learn how to match by method, path, headers, body, and more.
  </Card>

  <Card title="Response Actions" icon="reply" href="/mocking/response-actions">
    Return responses, forward requests, invoke callbacks, or simulate errors.
  </Card>
</CardGroup>
