To ensure all tests can run in parallel with completely isolated independent data use a unique value for each test. The unique value for a test should be specified in each request matcher for all expectations for that test. This ensures that expectations created by one test are not visible by other tests and therefore keeps test isolated without needing multiple separate instances of MockServer.

For example, if each test generates a unique value (i.e. a UUID) for the sessionId cookie or a correlationId header then this header or cookie can be specified in each expectation's request matcher ensuring only requests with that unique value could be matched against expectations with that unique value.

Note: the drawback with this approach is that the logs will be more complex to understand because there will be a large number of expectation match failures, therefore it is recommended to either use a unique instance of MockServer per test or to run tests in series and clear all expectations prior to each test.

Cleaner isolation — separate instances: the simplest way to get complete isolation between parallel tests is to run a separate MockServer instance per test (a different port, or a separate container). Each test then owns its own expectations and event log, so there is no cross-test interference and no need to thread a unique value through every matcher. The unique-value technique above is the right choice only when sharing a single instance is unavoidable.

For the full set of recommendations — including how the shared event log behaves under load and how to avoid intermittent failures — see Verify Requests → Best practices for parallel tests and the Important notes for parallel testing section.

String sessionId = UUID.randomUUID().toString();

new MockServerClient("127.0.0.1", 1080)
    .when(
        request()
            .withMethod("GET")
            .withPath("/somePath")
            .withCookies(
                cookie("sessionId", sessionId)
            )
    )
    .respond(
        response()
            .withStatusCode(200)
            .withBody("{ \"name\": \"value\" }")
    );
function guid() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
        s4() + '-' + s4() + s4() + s4();
}

var sessionId = guid();

mockServerClient("localhost", 1080)
    .mockAnyResponse({
        'httpRequest': {
            'method': 'GET',
            'path': '/somePath',
            "cookies": {
                "sessionId": sessionId
            }
        },
        'httpResponse': {
            'statusCode': 200,
            'body': JSON.stringify({name: 'value'})
        }
    })
    .then(
        function () {
            console.log("expectation created");
        },
        function (error) {
            console.log(error);
        }
    );

See REST API for full JSON specification

import uuid
from mockserver.client import MockServerClient
from mockserver.models import HttpRequest, HttpResponse

session_id = str(uuid.uuid4())

client = MockServerClient("localhost", 1080)
client.when(
    HttpRequest.request(
        method="GET",
        path="/somePath"
    ).with_cookie("sessionId", session_id)
).respond(
    HttpResponse.response(body='{ "name": "value" }', status_code=200)
)
require 'securerandom'
require 'mockserver-client'

session_id = SecureRandom.uuid

client = MockServer::Client.new('localhost', 1080)
client.when(
    MockServer::HttpRequest.new(
        method: 'GET',
        path: '/somePath',
        cookies: [MockServer::KeyToMultiValue.new(
            name: 'sessionId', values: [session_id]
        )]
    )
).respond(
    MockServer::HttpResponse.new(
        status_code: 200,
        body: '{ "name": "value" }'
    )
)
import (
    "github.com/google/uuid"
    mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
)

sessionId := uuid.New().String()

client := mockserver.New("localhost", 1080)
client.When(
    mockserver.Request().
        Method("GET").
        Path("/somePath").
        Cookie("sessionId", sessionId),
).Respond(
    mockserver.Response().
        StatusCode(200).
        Body(`{ "name": "value" }`),
)
using MockServer.Client;
using MockServer.Client.Models;

var sessionId = Guid.NewGuid().ToString();

using var client = new MockServerClient("localhost", 1080);
client.When(
    HttpRequest.Request()
        .WithMethod("GET")
        .WithPath("/somePath")
        .WithCookie("sessionId", sessionId)
).Respond(
    HttpResponse.Response()
        .WithStatusCode(200)
        .WithBody("{ \"name\": \"value\" }")
);
use mockserver_client::{ClientBuilder, HttpRequest, HttpResponse};
use uuid::Uuid;

let session_id = Uuid::new_v4().to_string();

let client = ClientBuilder::new("localhost", 1080).build().unwrap();
client.when(
    HttpRequest::new()
        .method("GET")
        .path("/somePath")
        .cookie("sessionId", &session_id)
).respond(
    HttpResponse::new()
        .status_code(200)
        .body("{ \"name\": \"value\" }")
).unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
use MockServer\HttpResponse;

$sessionId = bin2hex(random_bytes(16));

$client = new MockServerClient('localhost', 1080);
$client->when(
    HttpRequest::request()
        ->method('GET')
        ->path('/somePath')
        ->cookie('sessionId', $sessionId)
)->respond(
    HttpResponse::response()
        ->statusCode(200)
        ->body('{ "name": "value" }')
);
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
  "httpRequest" : {
    "method" : "GET",
    "path" : "/somePath",
    "cookies" : {
      "sessionId" : "1e2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d"
    }
  },
  "httpResponse" : {
    "statusCode" : 200,
    "body" : "{ \"name\": \"value\" }"
  }
}'

See REST API for full JSON specification