Soklet Logo

Core Concepts

Automated Testing

An automated test harness is an important part of any system.

Soklet implicitly supports unit testing; types which contain your Resource Methods are Plain Old Java Objects that can be instantiated and used however you like.

Soklet explicitly supports integration testing by providing a Simulator along with special "networkless" HttpServer, SseServer, and McpServer implementations to which you can send requests and access responses that would ordinarily be sent over the wire to clients. Server-Sent Events and MCP are both fully supported as well. See Integration Testing for details.

Low-complexity testing is a design goal of Soklet.

All example code below uses JUnit Jupiter, but Soklet has no dependency on it - you may use any testing framework you like.


Unit Testing

The main concept of unit testing is to test a method or behavior in isolation.

Because Soklet does not impose constraints on your types, instantiating and injecting mock dependencies is straightforward. You might build your own mocks or use a library like Mockito.

Let's define a ReverseResource and exercise it with unit tests.

public class ReverseResource {
  // Reverse the input
  @POST("/reverse")
  public List<Integer> reverse(@RequestBody List<Integer> numbers) {
    List<Integer> reversed = new ArrayList<>(numbers);
    Collections.reverse(reversed);
    return reversed;
  }

  // Reverse the input and set custom headers/cookies
  @POST("/reverse-again")
  public Response reverseAgain(@RequestBody List<Integer> numbers) {
    Integer largest = Collections.max(numbers);
    Instant lastRequest = Instant.now();

    return Response.withStatusCode(200)
      .headers(Map.of("X-Largest", List.of(String.valueOf(largest))))
      .cookies(List.of(
        ResponseCookie.with("lastRequest", lastRequest.toString()).build()
      ))
      .body(reverse(numbers))
      .build();
  }
}

Unit tests for our ReverseResource:

// Pull in JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

@Test
public void reverseUnitTest() {
  // This is a Plain Old Java Object, no Soklet dependency
  ReverseResource resource = new ReverseResource();

  List<Integer> input = List.of(1, 2, 3);
  List<Integer> expected = List.of(3, 2, 1);
  List<Integer> actual = resource.reverse(input);

  assertEquals(expected, actual, "Reverse failed");
}

@Test
public void reverseAgainUnitTest() {
  ReverseResource resource = new ReverseResource();
  List<Integer> input = List.of(1, 2, 3);

  // Set expectations
  List<Integer> expectedBody = List.of(3, 2, 1);
  Integer expectedCode = 200;
  Integer expectedLargest = Collections.max(input);
  Instant lastRequestAfter = Instant.now();

  Response response = resource.reverseAgain(input);

  // Extract actuals
  Integer actualCode = response.getStatusCode();
  List<Integer> actualBody = (List<Integer>) response.getBody().orElseThrow();

  Integer actualLargest = response.getHeaders().get("X-Largest").stream()
    .findAny()
    .map(value -> Integer.valueOf(value))
    .orElseThrow();

  Instant actualLastRequest = response.getCookies().stream()
    .filter(responseCookie -> responseCookie.getName().equals("lastRequest"))
    .findAny()
    .map(responseCookie -> Instant.parse(responseCookie.getValue().orElseThrow()))
    .orElseThrow();

  // Verify expectations vs. actuals
  assertEquals(expectedCode, actualCode, "Bad status code");
  assertEquals(expectedBody, actualBody, "Reverse failed");
  assertEquals(expectedLargest, actualLargest, "Largest header failed");
  assertTrue(actualLastRequest.isAfter(lastRequestAfter), "Last request too early");
}

Integration Testing

Integration testing concerns itself with exercising a system or one of its subsystems as a whole, simulating real-world behavior as closely as possible.

Real Listener Tests

Use scoped Soklet.run(config, action) when you need to exercise the actual HTTP transport. This complete JUnit Jupiter test configures a loopback listener and resource, gives the request finite deadlines, and closes the HTTP client before scoped shutdown:

import com.soklet.HttpServer;
import com.soklet.LifecyclePolicy;
import com.soklet.ResourceMethodResolver;
import com.soklet.Soklet;
import com.soklet.SokletConfig;
import com.soklet.annotation.GET;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.parallel.ResourceLock;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class HealthIntegrationTest {
  @Test
  @Timeout(20)
  @ResourceLock("soklet-test-http-port")
  public void servesHealthCheck() throws Exception {
    int port = Integer.getInteger("soklet.test.port", 18080);
    SokletConfig config = SokletConfig.withHttpServer(
        HttpServer.withPort(port).host("127.0.0.1").build())
      .resourceMethodResolver(ResourceMethodResolver.fromClasses(
        Set.of(HealthResource.class)))
      .lifecyclePolicy(LifecyclePolicy.builder()
        .startupTimeout(Duration.ofSeconds(5))
        .startupCancelationTimeout(Duration.ofSeconds(1))
        .gracefulShutdownTimeout(Duration.ofSeconds(1))
        .forcedShutdownTimeout(Duration.ofSeconds(1))
        .build())
      .build();

    Soklet.run(config, () -> {
      // Real listeners are ready before this callback starts.
      try (HttpClient client = HttpClient.newBuilder()
          .connectTimeout(Duration.ofSeconds(2)).build()) {
        HttpRequest request = HttpRequest.newBuilder(
            URI.create("http://127.0.0.1:" + port + "/health"))
          .timeout(Duration.ofSeconds(2))
          .GET().build();
        HttpResponse<String> response = client.send(
          request, HttpResponse.BodyHandlers.ofString());
        assertEquals(200, response.statusCode());
        assertEquals("OK", response.body());
      }
    });
  }

  public static class HealthResource {
    @GET("/health")
    public String health() {
      return "OK";
    }
  }
}

Save this as HealthIntegrationTest.java in your test sources and add JUnit Jupiter to your test dependencies. Explicit resource registration makes this example independent of generated route discovery; application builds using annotated classpath discovery still need the annotation processor setup.

The example uses port 18080; set -Dsoklet.test.port=... to a port allocated to your test process. @ResourceLock serializes tests using the same key within one JUnit run. It does not reserve a port against other JVMs or applications. Give parallel CI workers separate ports and use the same lock for tests that share a listener port.

Construct fresh transports for each test. The callback receives no lifecycle handle. Returning or throwing requests shutdown and joins finalization, so an assertion failure cannot skip teardown. The callback's own work needs its request/test deadlines; Soklet's lifecycle budgets do not impose a callback timeout. See Application Lifecycle for error and interruption behavior.

Networkless Integration Tests

Running tests of this nature for web-based applications has traditionally been awkward and complicated; Soklet attempts to lower this barrier. You are encouraged to think of your system as a collection of reusable components capable of running in any context, not just code that "lives inside" a web server.

To facilitate integration testing, Soklet provides SokletSimulator::run(SokletConfig, Simulation). Pass it the same completed SokletConfig that describes the application. For every call, Soklet creates fresh, transport-isolated networkless counterparts for the HTTP, SSE, and MCP transports present in that configuration. The simulator call never starts, claims, or changes the source transport objects, and it opens no ports or sockets.

If teardown cannot prove that all tracked work finished, a successful simulation body is followed by SokletShutdownIncompleteException. If the body already failed, the teardown exception is suppressed on that original failure. Its message identifies component dispositions and residual-activity categories, such as an HTTP callback or SSE stream still running. Outstanding work alone has no Throwable cause; inspect getShutdownResult() and each component's getResidualActivityEvidence() for the frozen evidence. A worker finishing later does not change that result.

The lifecycle result and evidence objects have bounded toString() diagnostics containing enum categories, failure counts/presence and residual-component counts when available. They do not invoke application Throwables, traverse retained objects, or render free-text residual summaries. Use the typed accessors for details; the diagnostic strings are not a serialization format.

The derived graph retains the application's behavior with fresh framework-owned transport runtime state. Explicitly configured collaborators such as the ResourceMethodResolver, InstanceProvider, interceptors, and metrics collector are reused by identity. Unset defaults that depend on the completed configuration are derived again. When the application has MCP, Soklet clones its server construction settings into a fresh simulated McpServer. Application-supplied MCP collaborators, including rate limiters, are reused by identity; tests remain responsible for isolating their mutable state.

This is transport isolation, not a deep copy of the application object graph. Soklet does not inspect or rebind a dependency-injection provider, service, or other collaborator that captured a source transport; it continues to reference the source object. Supply a test-scoped collaborator when necessary.

Use SimulatorConfig::fromSokletConfig when an API expects a completed simulator configuration. Use SimulatorConfig::withSokletConfig when one test needs overrides before build(). Later calls on the returned builder take precedence over imported settings. For example, configureMcpServer(Consumer) customizes the imported MCP construction while preserving the framework-owned build lifecycle, and it can replace a shared collaborator with a test-scoped implementation. If no MCP server was imported, the same method creates a fresh one from the standard MCP builder defaults.

Every transport present in the source configuration remains present in this imported shape. If a test must omit one, use the standalone SimulatorConfig::builder form and configure only the intended transports and application settings.

For a standalone, transport-isolated simulation with no application configuration, start with SimulatorConfig::builder, then add the fresh HTTP and SSE transports with httpServer() and sseServer(). Call configureMcpServer(Consumer) to add MCP. Its fresh builder's logical port defaults to 0; override it with port(Integer) when a test needs another logical value. It uses the same generated-endpoint discovery and accept-all admission defaults as McpServer::withPort. Configure the required MCP settings shown in Server Configuration on that supplied builder. Tool rate limiting is optional, just as on the live server. In every case, a completed SimulatorConfig can be claimed by exactly one run and must not be reused.

The examples below assume obtainMySokletConfig() returns the application's completed configuration.

The direct form is the default choice. Derive a configuration explicitly only when a test needs to keep it or override an imported setting:

// Fresh graph, same application behavior.
SokletSimulator.run(obtainMySokletConfig(), simulator -> {
  // assertions
});

// Fresh graph with one test-only MCP override.
SimulatorConfig simulatorConfig = SimulatorConfig
  .withSokletConfig(obtainMySokletConfig())
  .configureMcpServer(builder -> builder
    .requestTimeout(Duration.ofSeconds(2)))
  .build();

A built SimulatorConfig can be claimed by exactly one run. A second SokletSimulator.run(...) with the same instance throws IllegalStateException, so build a new one for each run. The same SokletConfig can be passed to any number of runs.

Simulation exercises application dispatch, interceptors, marshaling, and lifecycle observation. It starts from a built Request, so it does not reproduce socket parsing, HTTP request-header/body/handler timeouts, or network backpressure, and it does not invoke the HTTP server’s IdGenerator or MultipartParser. Test those boundaries separately through a real listener. For example, perhaps you have configured your application to:

The transaction pattern must explicitly mark handled failures for rollback, because response generation returns an error response instead of propagating the original Throwable. Assert database state and post-commit side effects after a failing request as well as its HTTP status.

These would all occur when running on the Simulator, just like they would for real client requests.

See Real-World Examples

The Toy Store App documentation has its own suite of integration tests - they exercise talking to a database, accepting and returning JSON, and more.

The HTTP simulator preserves the supplied request body: an explicitly supplied empty byte[] is present. The built-in HTTP server normalizes an empty wire body to absence. Leave the body unset to model a missing body; a required @RequestBody can therefore behave differently if a simulation explicitly supplies an empty array. Use a real listener to test wire-level body normalization.

Marshaled Responses

Your ResponseMarshaler produces MarshaledResponse instances as output - these encapsulate what ultimately gets sent over the wire to the client. For example, a UTF-8 byte-array-backed representation of a JSON response body, as opposed to a Java object that is later marshaled to JSON.

Let's define a HelloResource...

public class HelloResource {
  // Respond with a friendly message
  @GET("/hello")
  public String hello(@QueryParameter String name) {
    return String.format("Hello, %s", name);
  }
}

...and exercise it with an integration test.

Invoking Simulator::performHttpRequest simulates a client request - without touching the network - and returns a HttpRequestResult, which can be examined to determine the request's outcome.

@Test
public void integrationTest() {
  SokletSimulator.run(
    obtainMySokletConfig(),
    simulator -> {
    // Construct a request.
    // The `withPath` builder assumes paths and query parameters
    // are already decoded, which is normally what you want for tests.
    // It also uses the path exactly as given: `.`, `..`, `//` and a trailing
    // slash are kept, where the wire and `withRawUrl` normalize them.
    // But you can also construct with a "raw" encoded URL + query, e.g.
    // Request.withRawUrl(HttpMethod.GET, "/hello?name=Mark%20Test")
    Request request = Request.withPath(HttpMethod.GET, "/hello")
      .queryParameters(Map.of("name", List.of("Mark")))
      .build();

    // Perform the request and get a handle to its result...
    HttpRequestResult result = simulator.performHttpRequest(request);
    // ...and get the finalized response that would have gone over the wire.
    MarshaledResponse marshaledResponse = result.getMarshaledResponse();

    // Verify status code
    Integer expectedCode = 200;
    Integer actualCode = marshaledResponse.getStatusCode();
    assertEquals(expectedCode, actualCode, "Bad status code");

    // Verify response body.
    // Here we turn UTF-8 bytes back into a String
    MarshaledResponseBody body = marshaledResponse.getBody().orElse(null);
    if (body instanceof MarshaledResponseBody.Bytes bytesBody) {
      String expectedBody = "Hello, Mark";
      String actualBody = new String(bytesBody.getBytes(), StandardCharsets.UTF_8);
      assertEquals(expectedBody, actualBody, "Bad response body");
    } else {
      fail("No byte-array-backed response body");
    }
    }
  );
}

For ordinary HTTP simulator results, finite file, secure-file, file-channel, and ByteBuffer bodies are materialized into MarshaledResponseBody.Bytes. Assert the resulting bytes, regardless of how the handler supplied them:

MarshaledResponseBody.Bytes body = assertInstanceOf(
  MarshaledResponseBody.Bytes.class,
  marshaledResponse.getBody().orElseThrow()
);
assertArrayEquals("public".getBytes(StandardCharsets.UTF_8), body.getBytes());

Use a small fixture so the simulator does not need to retain a large body. To verify descriptor-specific properties such as file path, offset, or ByteBuffer slice, unit-test the handler or StaticFiles result directly before giving it to the simulator. A direct StaticFiles result uses MarshaledResponseBody.SecureFile; reading it through openChannel() requires closing that channel. Use a real HTTP client for transfer behavior, socket backpressure, and large responses.

Streaming Responses

For ordinary HTTP simulator requests, StreamingResponseBody responses are materialized into a byte-array-backed MarshaledResponseBody.Bytes so tests can inspect the final body without opening a socket. Streaming producers run synchronously on the calling thread. An admitted call waits for LifecycleObserver::didTerminateResponseStream to finish before returning, so observer effects can be asserted immediately. A blocked producer or observer can block that call. Unadmitted rejection observations use a separate bounded asynchronous path and may finish later.

The simulator ignores HTTP streaming total and idle timeout settings: ResponseStream.getDeadline() and getIdleTimeout() are empty. Cleanup supervision, scope shutdown and output-capture limits still apply. Use a real HTTP fixture to test response deadlines, socket backpressure and committed partial delivery.

A producer failure that wins termination throws IllegalStateException with the original cause after termination observation, without returning a partial HttpRequestResult; an application Error is rethrown when it wins that outcome. In real HTTP, status and headers have already been committed before the producer runs, so a failure aborts the body while retaining that status. Both paths report PRODUCER_FAILED with the original cause for that outcome; an earlier elected cancelation still wins.

For a successful stream:

SokletSimulator.run(
  obtainMySokletConfig(),
  simulator -> {
  HttpRequestResult result = simulator.performHttpRequest(
    Request.withPath(HttpMethod.GET, "/export").build()
  );

  byte[] bytes = ((MarshaledResponseBody.Bytes) result
    .getMarshaledResponse()
    .getBody()
    .orElseThrow()).getBytes();

  assertEquals("first\nsecond\n", new String(bytes, StandardCharsets.UTF_8));
  }
);

Use SimulatorOptions when you need to cap how much streaming output a test may materialize:

SimulatorOptions options = SimulatorOptions.builder()
  .streamingResponseBodyLimitInBytes(1_024 * 1_024)
  .build();

SokletSimulator.run(
  SimulatorConfig.withSokletConfig(obtainMySokletConfig())
    .simulatorOptions(options)
    .build(),
  simulator -> {
  simulator.performHttpRequest(Request.withPath(HttpMethod.GET, "/export").build());
  }
);

If the stream exceeds the configured limit, the simulator cancels the stream with SIMULATOR_LIMIT_EXCEEDED, invokes the stream-termination lifecycle hook, and surfaces the failure to the test.

Logical Responses

HttpRequestResult also provides access to the logical Response, determined by the object returned by the Resource Method (if available). This lets you see what the response body looks like pre-marshaling.

For example, let's define a Toy and a Resource Method which vends a list of them...

record Toy(
  String name,
  Double price,
  Currency currency
) {}

public class ToyResource {
  @GET("/toys")
  public List<Toy> toys() {
    return List.of(
      new Toy("Basketball", 25.99, Currency.getInstance("USD")),
      new Toy("Bola de futebol", 9499.00, Currency.getInstance("BRL"))
    );
  }
}

...then, simulate a call to GET /toys and pull the logical Response returned by the Resource Method:

SokletSimulator.run(
  obtainMySokletConfig(),
  simulator -> {
  Request request = Request.fromPath(HttpMethod.GET, "/toys");

  // Perform the request and get a handle to its result...
  HttpRequestResult result = simulator.performHttpRequest(request);
  // ...and get the "pre-marshaling" response.
  Response response = result.getResponse().orElseThrow();

  // Does the Toy data look like we expect?
  List<Toy> toys = (List<Toy>) response.getBody().orElseThrow();
  assertTrue(toys.size() == 2, "Wrong number of Toys");

  Toy expectedToy = new Toy("Basketball", 25.99, Currency.getInstance("USD"));
  Toy actualToy = toys.get(0);
  assertEquals(expectedToy, actualToy, "Unexpected Toy");
  }
);

CORS Responses

If you'd like to ensure your CORS configuration is correct, you might examine HttpRequestResult::getCorsPreflightResponse to verify it.

Here we make an OPTIONS request with Origin and Access-Control-Request-Method headers to simulate a CORS preflight, just like a browser would do. We verify that Soklet approves the preflight and responds appropriately.

// Specify an origin to whitelist for CORS...
String corsOrigin = "https://example.soklet.com";

// ...and tell Soklet about it.
SimulatorConfig simulatorConfig = SimulatorConfig.builder()
  .httpServer()
    .resourceMethodResolver(ResourceMethodResolver.fromClasses(
      Set.of(HelloResource.class)
    ))
    .corsAuthorizer(CorsAuthorizer.fromWhitelistedOrigins(
      Set.of(corsOrigin)
    ))
    .build();

SokletSimulator.run(
  simulatorConfig,
  simulator -> {
  // Make a CORS preflight request...
  Request request = Request.withPath(HttpMethod.OPTIONS, "/hello")
    .headers(Map.of(
      "Origin", List.of(corsOrigin),
      "Access-Control-Request-Method", List.of("GET")
    ))
    .build();

  HttpRequestResult result = simulator.performHttpRequest(request);

  // ...and verify that Soklet has set the
  // Access-Control-Allow-Origin response header correctly.
  CorsPreflightResponse corsPreflightResponse =
    result.getCorsPreflightResponse().orElseThrow();

  String expectedHeader = corsOrigin;
  String actualHeader = corsPreflightResponse.getAccessControlAllowOrigin();
  assertEquals(expectedHeader, actualHeader, "Wrong CORS preflight header");
  }
);

Server-Sent Events

Simulated SSE enforces streamingLifecycleCapacity, but it does not enforce the live transport's concurrentConnectionLimit. Use a real SSE listener to test that connection cap; lowering it in the source configuration does not add an equivalent simulator limit.

An accepted SseRequestResult.HandshakeAccepted is AutoCloseable. Its unchecked, idempotent close() simulates a client disconnect, even if no event consumer was registered. Use try-with-resources when a test should end that connection before the simulator scope ends. Scope teardown terminates all remaining accepted connections with SERVER_STOPPING. Closed handles retain result metadata but reject new consumers and writes; an initializer that ignores interruption can still outlive teardown.

The configured LifecycleObserver and MetricsCollector receive SSE connection establishment and termination callbacks. A lifetime uses the same immutable SseConnection metadata snapshot throughout. An initializer failure after acceptance still receives establishment followed by termination. Both termination callbacks share the first elected StreamTermination, including its original cause and duration measured at election.

Terminal callbacks run asynchronously after delivery state is released and establishment callbacks finish. close() does not wait for application observers; use a timed latch in your observer when asserting termination inside the simulation. Scope teardown waits within its lifecycle budgets. A blocked observer remains accounted for until it returns and can cause incomplete teardown. Failed handshakes use a separate bounded observation allowance; excess notifications are omitted with a log event. Typed simulator delivery does not emit broadcast/drop metrics, socket-write callbacks or byte/write-duration metrics.

A failing, overflowing or terminated accepted initializer makes performSseRequest throw rather than return an active handle. Accepted handshake headers alone do not guarantee activation. Consumer calls run synchronously on the broadcasting or registration thread; a slow consumer delays that caller and other clients in the same broadcast. The separate pending-delivery bound covers reentrant/concurrent delivery, while simulation does not reproduce network backpressure.

The first event or comment consumer starts simulated client reading. After that, new payloads of types without a consumer are discarded. An event-only test can therefore continue reading events even when the application broadcasts comments. Payloads already captured before reading, including initializer output, remain available to a consumer registered later. Register both consumers before driving application broadcasts if you need to observe both types; a late registration does not replay discarded payloads.

Before the first registration, combined event/comment capture is bounded by connectionQueueCapacity, which defaults to 128. Pending deliveries to registered consumers share a separate bound of the same size. Each buffer can retain at most that many payloads, excluding consumer calls in progress; these counts do not bound payload bytes. An unread client or a blocked listener can still overflow its buffer and disconnect with BACKPRESSURE. Closing the accepted handle clears both buffers, while unfinished consumer calls remain tracked until they return.

The simulator snapshots the built-in HTTP and SSE lifecycle settings from the supplied SokletConfig. Custom transport implementations use simulator defaults. Noncooperative application work can outlive the bounded simulator teardown and is reported as residual work.

If your system uses Server-Sent Events, you can use Soklet's Simulator::performSseRequest to perform an SSE "handshake" and then broadcast events as usual. You can also act as a client, listening for Server-Sent Event and Comment payloads to verify they are transmitted as expected.

Let's assume we have an Event Source Method available at resource path /chats/{chatId}/event-source which lets clients listen for chat messages...

public class ChatResource {
  @SseEventSource("/chats/{chatId}/event-source")
  public SseHandshakeResult chatEventSource(@PathParameter Long chatId) {
    // Accept everyone, no special behavior
    return SseHandshakeResult.accept();
  }
}

...and a ChatService backend which broadcasts new messages to the chat:

public class ChatService {
  private SseServer sseServer;

  // Accepts a reference to SseServer,
  // which provides SSE broadcasters on-demand
  public ChatService(SseServer sseServer) {
    this.sseServer = sseServer;
  }

  public void createChatMessage(Long chatId, String message) {
    // Construct a path for the appropriate Event Source...
    String eventSourcePath = String.format(
      "/chats/%s/event-source", chatId
    );

    ResourcePath resourcePath = ResourcePath.fromPath(eventSourcePath);

    // ...construct the chat message payload...
    SseEvent event = SseEvent.withEvent("chat-message")
      .data(message)
      .build();

    // ...and send it to all connected clients.
    sseServer.acquireBroadcaster(resourcePath)
      .ifPresent(broadcaster -> broadcaster.broadcastEvent(event));
  }
}

We can now write an integration test that exercises Server-Sent Events from both client and server perspectives.

AtomicReference<SseServer> sseServer = new AtomicReference<>();

SokletSimulator.run(
  SimulatorConfig.withSokletConfig(obtainMySokletConfig())
    .sseServer(sseServer::set)
    .build(),
  simulator -> {
  // Provide our ChatService with this scope's networkless SseServer
  // so it can acquire broadcasters to send SSE payloads.
  ChatService chatService = new ChatService(sseServer.get());

  // Create a request for an SSE Event Source...
  final Long CHAT_ID = 123L;
  String eventSourcePath = String.format("/chats/%s/event-source", CHAT_ID);
  Request request = Request.fromPath(HttpMethod.GET, eventSourcePath);

  // ...and perform it and get a handle to the result.
  SseRequestResult result =
    simulator.performSseRequest(request);

  // The Simulator provides 3 logical outcomes for SSE connections:
  // * Accepted handshake (connection stays open)
  // * Rejected handshake (explicit rejection - connection closed)
  // * Request failed (implicit rejection, e.g. uncaught exception - connection closed)
  switch (result) {
    // Happy path: handshake was accepted
    case HandshakeAccepted handshakeAccepted -> {
      // Single-shot latch; we'll wait until a Server-Sent Event comes through
      CountDownLatch countDownLatch = new CountDownLatch(1);

      // Listen for Server-Sent Events
      handshakeAccepted.registerEventConsumer((sseEvent) -> {
        // Once we see an event come through, unlatch and end the test
        countDownLatch.countDown();
      });

      // On a separate thread, broadcast a Server-Sent Event
      new Thread(() -> {
        chatService.createChatMessage(CHAT_ID, "test message");
      }).start();

      // Wait a bit for unlatch
      try {
        assertTrue(countDownLatch.await(5, TimeUnit.SECONDS), "Did not receive a Server-Sent Event in time");
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        fail("Interrupted while waiting for a Server-Sent Event", e);
      }
    }

    // Handshake was rejected (should not happen here)
    case HandshakeRejected handshakeRejected -> {
      fail(String.format("SSE handshake rejected: %s", handshakeRejected));
    }

    // Request failed for some other reason (should not happen here)
    case RequestFailed requestFailed -> {
      fail(String.format("SSE request failed: %s", requestFailed));
    }
  }
  }
);

The Simulator can also listen for SSE comment broadcasts:

handshakeAccepted.registerCommentConsumer((comment) -> {
  System.out.printf("SSE comment (%s): %s\n",
    comment.getCommentType(),
    comment.getComment().orElse("<heartbeat>"));
});

You can also capture errors that occur while broadcasting or unicasting SSE payloads during tests:

SokletSimulator.run(
  obtainMySokletConfig(),
  simulator -> {
  simulator.onBroadcastError((throwable) -> {
    fail("Broadcast handler threw: " + throwable.getMessage());
  });

  simulator.onUnicastError((throwable) -> {
    fail("Unicast handler threw: " + throwable.getMessage());
  });
  }
);

An accepted initializer's unchecked exception or Error propagates unchanged from performSseRequest; a checked failure is wrapped in IllegalStateException. Queue overflow or termination before activation also prevents returning an active accepted connection. Termination observations still occur.

If your Event Source Method uses a client initializer to unicast events/comments during the handshake, those payloads are buffered and delivered to the first registered consumer in the simulator. Any errors thrown by your consumers are surfaced via the unicast error handler above.

Client context specified via SseHandshakeResult.Accepted.Builder::clientContext is preserved in the simulator, so keyed/memoized broadcasts will receive the same context values as they would in production.

For one memoized broadcast, the simulator invokes a provider once per key, including a null key. A provider exception or forbidden null payload is reported to onBroadcastError once per affected key; clients in other groups still receive their payloads. The cache ends with that broadcast, so the next call can retry. Key-selector and consumer failures remain per client. A consumer failure leaves the shared payload usable by the other clients. Without an error handler, or if it throws, provider failures are logged once per key with the affected client count and original cause. The simulator delivers typed payload objects; socket serialization is validated separately.

Here is a minimal keyed broadcast example in a test:

AtomicReference<SseServer> sseServer = new AtomicReference<>();

SokletSimulator.run(
  SimulatorConfig.withSokletConfig(obtainMySokletConfig())
    .sseServer(sseServer::set)
    .build(),
  simulator -> {
  Request request = Request.fromPath(HttpMethod.GET, "/chats/123/event-source");
  SseRequestResult result =
    simulator.performSseRequest(request);

  if (result instanceof HandshakeAccepted accepted) {
    accepted.registerEventConsumer((event) -> {
      System.out.printf("Event data: %s\n", event.getData().orElseThrow());
    });

    sseServer.get()
      .acquireBroadcaster(ResourcePath.fromPath("/chats/123/event-source"))
      .ifPresent(broadcaster -> broadcaster.broadcastEvent(
      (clientContext) -> (Locale) clientContext,
      (locale) -> SseEvent.withEvent("chat-message")
        .data(localizeMessageFor(locale))
        .build()
      ));
  } else {
    fail("Expected accepted handshake");
  }
  }
);

...and access the MarshaledResponse data as well:

// You might examine + verify response headers here...
MarshaledResponse marshaledResponse =
  handshakeAccepted.getHttpRequestResult().getMarshaledResponse();

// ...e.g. make sure this was set by Soklet
List<String> xAccelBufferingValues =
  marshaledResponse.getHeaders().getOrDefault("X-Accel-Buffering", List.of());

assertTrue(xAccelBufferingValues.contains("no"));

References:

Model Context Protocol

Soklet's Simulator starts an asynchronous, off-network MCP request through the same protocol processor, admission controller, handlers, lifecycle hooks, metrics, request-stream code, and subscription code used by the live server. Use Simulator::startMcpRequest with a complete request. It supports modern POSTs and explicitly configured 2025 session POST/GET/DELETE; GET requires effective notification families and GET/DELETE require transport admission. The simulator does not bind a port, start the listener, inject a Host, or rewrite caller-supplied request data.

The returned McpSimulation provides repeatable bounded waits for the response and terminal completion, destructive FIFO reads through awaitStreamItem(...), and idempotent disconnect through close(). McpSimulationOptions bounds pending stream items and total captured bytes. Ordinary JSON bodies are available through McpSimulationResponse; request-scoped progress and subscription frames are exposed as McpSimulationStreamItem values.

Simulation exercises the real application path but is intentionally off-network. It does not prove socket behavior, proxy integration, kernel backpressure, or live-client interoperability. See MCP for request construction, capture semantics, timeouts, stream termination reasons, and complete examples.

References:

See MCP for the current Simulator::startMcpRequest, McpSimulation, McpSimulationOptions, McpSimulationResponse, McpSimulationCompletion, and McpSimulationStreamItem contracts.

Previous
CORS