### Non-Spring GrpcMock Instance Setup Source: https://github.com/fadelis/grpcmock/blob/master/README.md For non-Spring setups, manually build and start a GrpcMock instance to manage it within your test class. ```java class TestClass { private GrpcMock grpcMock = GrpcMock.grpcMock().build().start(); } ``` -------------------------------- ### Programmatic gRPC Mock Server Management Source: https://context7.com/fadelis/grpcmock/llms.txt Examples for initializing mock servers, registering stubs, verifying interactions, and managing server lifecycles. ```java import org.grpcmock.GrpcMock; // Create server with random port GrpcMock grpcMock = GrpcMock.grpcMock().build().start(); int port = grpcMock.getPort(); // Create server with specific port GrpcMock grpcMock = GrpcMock.grpcMock(50051).build().start(); // Create in-process server with auto-generated name GrpcMock inProcessMock = GrpcMock.inProcessGrpcMock().build().start(); String serverName = inProcessMock.getInProcessName(); // Create in-process server with specific name GrpcMock inProcessMock = GrpcMock.inProcessGrpcMock("test-server").build().start(); // Register stubs using instance methods grpcMock.register(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response)); // Verify using instance methods grpcMock.verifyThat( calledMethod(SimpleServiceGrpc.getUnaryRpcMethod()).build(), CountMatcher.times(1)); // Reset all stubs grpcMock.resetAll(); // Stop the server grpcMock.stop(); // Configure global static instance GrpcMock.configureFor(grpcMock); // Now static methods use this instance stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response)); // Full example test setup class ManualServerTest { private GrpcMock grpcMock; private ManagedChannel channel; @BeforeEach void setup() { grpcMock = GrpcMock.grpcMock().build().start(); GrpcMock.configureFor(grpcMock); channel = ManagedChannelBuilder.forAddress("localhost", grpcMock.getPort()) .usePlaintext() .build(); } @AfterEach void teardown() { Optional.ofNullable(channel).ifPresent(ManagedChannel::shutdownNow); grpcMock.stop(); } @Test void testManualSetup() { stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response)); SimpleServiceBlockingStub stub = SimpleServiceGrpc.newBlockingStub(channel); assertThat(stub.unaryRpc(request)).isEqualTo(response); verifyThat(SimpleServiceGrpc.getUnaryRpcMethod()); } } ``` -------------------------------- ### Spring-Boot GrpcMock Instance Setup Source: https://github.com/fadelis/grpcmock/blob/master/README.md In a Spring-Boot test setup, autowire the GrpcMock instance to use it in multithreaded scenarios. ```java @SpringJUnitConfig @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.NONE) @AutoConfigureGrpcMock class TestClass { @Autowire private GrpcMock grpcMock; } ``` -------------------------------- ### Multithreaded Test Setup with GrpcMock Instance Source: https://context7.com/fadelis/grpcmock/llms.txt In multithreaded environments, inject the GrpcMock instance and use its methods for registering stubs and verifying calls. ```java @SpringBootTest(classes = Application.class) @AutoConfigureGrpcMock class MultithreadedTest { @Autowired private GrpcMock grpcMock; @Test void testInMultithreadedEnvironment() { // Use instance methods instead of static when threads differ grpcMock.register(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response)); // Execute test... grpcMock.verifyThat( calledMethod(SimpleServiceGrpc.getUnaryRpcMethod()).build(), CountMatcher.once()); } } ``` -------------------------------- ### Install gRPC Mock Maven Dependencies Source: https://context7.com/fadelis/grpcmock/llms.txt Add these dependencies to your Maven project to use the core library, Spring Boot integration, or JUnit5 support. ```xml org.grpcmock grpcmock-core 1.0.0 ``` ```xml org.grpcmock grpcmock-spring-boot 1.0.0 ``` ```xml org.grpcmock grpcmock-junit5 1.0.0 ``` -------------------------------- ### Configuring GrpcMock in BeforeEach Method Source: https://github.com/fadelis/grpcmock/blob/master/README.md If the `BeforeEach` method runs on the same thread as the test method, you can configure GrpcMock there to ensure consistent setup. ```java @BeforeEach void setup() { configureFor(grpcMock); } ``` -------------------------------- ### Using configureFor with GrpcMock Instance Source: https://github.com/fadelis/grpcmock/blob/master/README.md Alternatively, use the `configureFor` method with your GrpcMock instance at the beginning of each test to set up the configuration context. ```java @Test void should_test_something() { configureFor(grpMock); stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response)); ... test code verifyThat(calledMethod(SimpleServiceGrpc.getUnaryRpcMethod())); } ``` -------------------------------- ### In-Process gRPC Server for Faster Tests Source: https://context7.com/fadelis/grpcmock/llms.txt Utilize InProcessGrpcMockExtension for faster testing by running the mock server in-process. Set up the ManagedChannel using InProcessChannelBuilder. ```java // Using in-process server for faster tests @ExtendWith(InProcessGrpcMockExtension.class) class InProcessServiceTest { private ManagedChannel channel; @BeforeEach void setup() { channel = InProcessChannelBuilder.forName(GrpcMock.getGlobalInProcessName()) .usePlaintext() .build(); } @Test void testWithInProcessServer() { stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response)); SimpleServiceBlockingStub stub = SimpleServiceGrpc.newBlockingStub(channel); assertThat(stub.unaryRpc(request)).isEqualTo(response); } } ``` -------------------------------- ### Programmatic Configuration with @RegisterExtension Source: https://context7.com/fadelis/grpcmock/llms.txt Configure GrpcMock programmatically using @RegisterExtension with GrpcMockExtension.builder(). This allows customization of port, interceptors, and transport security. ```java // Programmatic configuration with @RegisterExtension class ConfiguredServerTest { @RegisterExtension static GrpcMockExtension grpcMock = GrpcMockExtension.builder() .withPort(0) // Random port .withInterceptor(new LoggingInterceptor()) .withTransportSecurity("/path/to/cert.pem", "/path/to/key.pem") .build(); private ManagedChannel channel; @BeforeEach void setup() { channel = ManagedChannelBuilder.forAddress("localhost", GrpcMock.getGlobalPort()) .usePlaintext() .build(); } @Test void testWithCustomConfiguration() { stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response)); SimpleServiceBlockingStub stub = SimpleServiceGrpc.newBlockingStub(channel); assertThat(stub.unaryRpc(request)).isEqualTo(response); } } ``` -------------------------------- ### Configure JUnit 5 Programmatically Source: https://github.com/fadelis/grpcmock/blob/master/README.md Use @RegisterExtension to configure the gRPC Mock server with custom settings like interceptors. ```java class TestClass { @RegisterExtension static GrpcMockExtension grpcMockExtension = GrpcMockExtension.builder() .withPort(0) .withInterceptor(new MyServerInterceptor()) .build(); private ManagedChannel channel; @BeforeEach void setupChannel() { channel = ManagedChannelBuilder.forAddress("localhost", GrpcMock.getGlobalPort()) .usePlaintext() .build(); } @AfterEach void shutdownChannel() { Optional.ofNullable(channel).ifPresent(ManagedChannel::shutdownNow); } } ``` -------------------------------- ### Full Configuration Options for gRPC Mock Source: https://context7.com/fadelis/grpcmock/llms.txt Customize gRPC Mock behavior with various options like port, server type, interceptors, thread count, and TLS settings. ```java @SpringBootTest(classes = Application.class) @AutoConfigureGrpcMock( port = 0, // Random port (recommended) useInProcessServer = false, // Use network server name = "", // Auto-generated name interceptors = {LoggingInterceptor.class}, // Custom interceptors executorThreadCount = 4, // Thread pool size certChainFile = "/path/to/cert.pem", // TLS certificate privateKeyFile = "/path/to/key.pem" // TLS private key ) class FullConfigurationTest { // Test implementation } ``` -------------------------------- ### Configure Spring Boot Test with In-Process Server Source: https://github.com/fadelis/grpcmock/blob/master/README.md Enable the in-process server mode by setting useInProcessServer to true in the annotation. ```java @SpringJUnitConfig @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.NONE) @AutoConfigureGrpcMock(useInProcessServer = true) class TestClass { @Value("${grpcmock.server.name}") private String inProcessName; private ManagedChannel channel; @BeforeEach void setupChannel() { channel = InProcessChannelBuilder.forName(inProcessName).build(); } @AfterEach void shutdownChannel() { Optional.ofNullable(channel).ifPresent(ManagedChannel::shutdownNow); } } ``` -------------------------------- ### JUnit5 Integration with Default Configuration Source: https://context7.com/fadelis/grpcmock/llms.txt Use GrpcMockExtension with the @ExtendWith annotation for automatic mock server management in JUnit5 tests. Ensure to set up and tear down the ManagedChannel. ```java import org.grpcmock.GrpcMock; import org.grpcmock.junit5.GrpcMockExtension; import org.grpcmock.junit5.InProcessGrpcMockExtension; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; // Using @ExtendWith annotation with default configuration @ExtendWith(GrpcMockExtension.class) class MyServiceTest { private ManagedChannel channel; @BeforeEach void setup() { channel = ManagedChannelBuilder.forAddress("localhost", GrpcMock.getGlobalPort()) .usePlaintext() .build(); } @AfterEach void teardown() { Optional.ofNullable(channel).ifPresent(ManagedChannel::shutdownNow); } @Test void testUnaryCall() { stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(expectedResponse)); SimpleServiceBlockingStub stub = SimpleServiceGrpc.newBlockingStub(channel); SimpleResponse response = stub.unaryRpc(request); assertThat(response).isEqualTo(expectedResponse); verifyThat(SimpleServiceGrpc.getUnaryRpcMethod()); } } ``` -------------------------------- ### Integrate JUnit 5 with InProcessGrpcMockExtension Source: https://github.com/fadelis/grpcmock/blob/master/README.md Use the in-process extension for faster unit test execution. ```java @ExtendWith(InProcessGrpcMockExtension.class) class TestClass { private ManagedChannel channel; @BeforeEach void setupChannel() { channel = InProcessChannelBuilder.forName(GrpcMock.getGlobalInProcessName()) .usePlaintext() .build(); } @AfterEach void shutdownChannel() { Optional.ofNullable(channel).ifPresent(ManagedChannel::shutdownNow); } } ``` -------------------------------- ### Configure Spring Boot Test with gRPC Mock Source: https://github.com/fadelis/grpcmock/blob/master/README.md Use @AutoConfigureGrpcMock to enable the mock server in a Spring Boot test environment. ```java @SpringJUnitConfig @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.NONE) @AutoConfigureGrpcMock class TestClass { @Value("${grpcmock.server.port}") private int grpcMockPort; private ManagedChannel channel; @BeforeEach void setupChannel() { channel = ManagedChannelBuilder.forAddress("localhost", grpcMockPort) .usePlaintext() .build(); } @AfterEach void shutdownChannel() { Optional.ofNullable(channel).ifPresent(ManagedChannel::shutdownNow); } } ``` -------------------------------- ### Using In-Process Server with Spring Boot Source: https://context7.com/fadelis/grpcmock/llms.txt Configure gRPC Mock to use an in-process server for testing by setting `useInProcessServer = true`. This avoids external network dependencies. ```java @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.NONE) @AutoConfigureGrpcMock(useInProcessServer = true) class InProcessSpringBootTest { @Value("${grpcmock.server.name}") private String inProcessName; private ManagedChannel channel; @BeforeEach void setup() { channel = InProcessChannelBuilder.forName(inProcessName).build(); } @Test void testWithInProcessServer() { stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response)); SimpleServiceBlockingStub stub = SimpleServiceGrpc.newBlockingStub(channel); assertThat(stub.unaryRpc(request)).isEqualTo(response); } } ``` -------------------------------- ### Add Spring Boot Dependency Source: https://github.com/fadelis/grpcmock/blob/master/README.md Include the grpcmock-spring-boot module in your Maven project. ```xml org.grpcmock grpcmock-spring-boot 1.0.0 ``` -------------------------------- ### Configure SLF4J Logging for JUnit 5 Source: https://github.com/fadelis/grpcmock/blob/master/README.md Set the logging level in simplelogger.properties when using the slf4j-simple backend. ```yaml org.slf4j.simpleLogger.log.org.grpcmock.GrpcMock=warn ``` -------------------------------- ### Add JUnit 5 Dependency Source: https://github.com/fadelis/grpcmock/blob/master/README.md Include the grpcmock-junit5 module in your Maven project. ```xml org.grpcmock grpcmock-junit5 1.0.0 ``` -------------------------------- ### Configuring Stubs with GrpcMock Instance Source: https://github.com/fadelis/grpcmock/blob/master/README.md Use the non-static methods of the GrpcMock instance directly within your test methods to register stubs and make assertions. ```java @Test void should_test_something() { grpcMock.register(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response)); ... test code grpcMock.verifyThat(calledMethod(SimpleServiceGrpc.getUnaryRpcMethod()).build(), CountMatcher.once()); } ``` -------------------------------- ### Stub Bidi Streaming gRPC Methods Source: https://github.com/fadelis/grpcmock/blob/master/README.md Use a StreamObserver to proxy bidi streaming calls based on the first request message. ```java stubFor(bidiStreamingMethod(SimpleServiceGrpc.getBidiStreamingRpcMethod()) .withHeader("header-1", "value-1") .withFirstRequest(req -> req.getRequestMessage().endsWith("1")) .willProxyTo(responseObserver -> new StreamObserver() { @Override public void onNext(SimpleRequest request) { SimpleResponse response = SimpleResponse.newBuilder() .setResponseMessage(request.getRequestMessage()) .build(); responseObserver.onNext(response); } @Override public void onError(Throwable error) { // handle error } @Override public void onCompleted() { responseObserver.onCompleted(); } })); ``` -------------------------------- ### Stub Server Streaming Methods Source: https://context7.com/fadelis/grpcmock/llms.txt Configure server streaming methods to return multiple responses in a stream with optional delays. Use `stream()` for custom streams, `response()` for individual responses, and `Status` for errors. ```java import static org.grpcmock.GrpcMock.*; // Return multiple responses in stream stubFor(serverStreamingMethod(SimpleServiceGrpc.getServerStreamingRpcMethod()) .willReturn(response1, response2, response3)); ``` ```java // Return stream using list List responses = Arrays.asList(response1, response2, response3); stubFor(serverStreamingMethod(SimpleServiceGrpc.getServerStreamingRpcMethod()) .willReturn(responses)); ``` ```java // Stream with individual delays for each response stubFor(serverStreamingMethod(SimpleServiceGrpc.getServerStreamingRpcMethod()) .willReturn(stream(response(response1).withFixedDelay(100)) .and(response(response2).withFixedDelay(50)) .and(response(response3).withFixedDelay(100)))); ``` ```java // Stream ending with error status stubFor(serverStreamingMethod(SimpleServiceGrpc.getServerStreamingRpcMethod()) .willReturn(stream(response1) .and(response2) .and(Status.INTERNAL.withDescription("Stream error")))); ``` ```java // With request predicate matching stubFor(serverStreamingMethod(SimpleServiceGrpc.getServerStreamingRpcMethod()) .withRequest(req -> req.getRequestMessage().contains("stream")) .willReturn(stream(response1).and(response2))); ``` ```java // Multiple scenarios for successive stream calls stubFor(serverStreamingMethod(SimpleServiceGrpc.getServerStreamingRpcMethod()) .willReturn(stream(response1).and(response2)) .nextWillReturn(stream(response3).and(response4)) .nextWillReturn(Status.UNAVAILABLE)); ``` ```java // Proxy to custom streaming implementation stubFor(serverStreamingMethod(SimpleServiceGrpc.getServerStreamingRpcMethod()) .willProxyTo((request, responseObserver) -> { responseObserver.onNext(response1); responseObserver.onNext(response2); responseObserver.onCompleted(); })); ``` -------------------------------- ### Verify gRPC Method Invocations in Java Source: https://context7.com/fadelis/grpcmock/llms.txt Verify method call counts, request parameters, headers, and status codes. Captured requests can also be retrieved for manual inspection. ```java import static org.grpcmock.GrpcMock.*; import static org.grpcmock.definitions.verification.CountMatcher.*; // Verify method was called exactly once verifyThat(SimpleServiceGrpc.getUnaryRpcMethod()); // Verify exact call count verifyThat(SimpleServiceGrpc.getUnaryRpcMethod(), times(3)); // Verify method was never called verifyThat(SimpleServiceGrpc.getUnaryRpcMethod(), never()); // Verify at least N calls verifyThat(SimpleServiceGrpc.getUnaryRpcMethod(), atLeast(2)); // Verify at most N calls verifyThat(SimpleServiceGrpc.getUnaryRpcMethod(), atMost(5)); // Verify with request matching verifyThat( calledMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .withRequest(expectedRequest), times(2)); // Verify with header matching verifyThat( calledMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .withHeader("authorization", "Bearer token123") .withHeader("x-request-id", value -> value.startsWith("req-")), times(1)); // Verify with status code matching verifyThat( calledMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .withStatusOk(), times(3)); verifyThat( calledMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .withStatusCode(Status.Code.INVALID_ARGUMENT), once()); // Verify combined conditions verifyThat( calledMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .withStatusOk() .withHeader("x-correlation-id", "abc123") .withRequest(expectedRequest), times(2)); // Verify client streaming with multiple requests matching verifyThat( calledMethod(SimpleServiceGrpc.getClientStreamingRpcMethod()) .withNumberOfRequests(3) .withFirstRequest(firstRequest) .withRequestAtIndex(1, secondRequest) .withRequestsContaining(specificRequest), once()); // Get captured requests for inspection List> captured = capturedRequestsFor( calledMethod(SimpleServiceGrpc.getUnaryRpcMethod())); assertThat(captured).hasSize(5); assertThat(captured.get(0).requests()).containsExactly(expectedRequest); ``` -------------------------------- ### Stub Client Streaming Methods Source: https://context7.com/fadelis/grpcmock/llms.txt Handle client streaming calls where the client sends multiple requests and receives a single response. Use `withFirstRequest()` to match based on the initial request, and `withHeader()`/`withoutHeader()` for header matching. ```java import static org.grpcmock.GrpcMock.*; import org.grpcmock.util.FunctionalResponseObserver; // Basic client streaming stub stubFor(clientStreamingMethod(SimpleServiceGrpc.getClientStreamingRpcMethod()) .willReturn(response)); ``` ```java // Match based on first request in stream stubFor(clientStreamingMethod(SimpleServiceGrpc.getClientStreamingRpcMethod()) .withFirstRequest(SimpleRequest.newBuilder().setRequestMessage("start").build()) .willReturn(response)); ``` ```java // Match first request with predicate stubFor(clientStreamingMethod(SimpleServiceGrpc.getClientStreamingRpcMethod()) .withFirstRequest(req -> req.getRequestMessage().startsWith("init")) .willReturn(response)); ``` ```java // With header matching stubFor(clientStreamingMethod(SimpleServiceGrpc.getClientStreamingRpcMethod()) .withHeader("x-stream-id", "stream-123") .withoutHeader("x-debug") .willReturn(response)); ``` ```java // Response with delay stubFor(clientStreamingMethod(SimpleServiceGrpc.getClientStreamingRpcMethod()) .willReturn(response(response).withFixedDelay(200))); ``` ```java // Error response stubFor(clientStreamingMethod(SimpleServiceGrpc.getClientStreamingRpcMethod()) .willReturn(statusException(Status.RESOURCE_EXHAUSTED))); ``` ```java // Sequential responses for multiple calls stubFor(clientStreamingMethod(SimpleServiceGrpc.getClientStreamingRpcMethod()) .willReturn(response1) .nextWillReturn(response2) .nextWillReturn(Status.DEADLINE_EXCEEDED)); ``` ```java // Proxy with custom stream observer handling stubFor(clientStreamingMethod(SimpleServiceGrpc.getClientStreamingRpcMethod()) .willProxyTo(responseObserver -> FunctionalResponseObserver.builder() .onNext(request -> System.out.println("Received: " + request.getRequestMessage())) .onCompleted(() -> { responseObserver.onNext(SimpleResponse.newBuilder() .setResponseMessage("Stream completed") .build()); responseObserver.onCompleted(); }) .build())); ``` -------------------------------- ### Configure Spring Boot Logging Source: https://github.com/fadelis/grpcmock/blob/master/README.md Adjust the logging level for GrpcMock in your application-test.yml file. ```yaml logging.level.org.grpcmock.GrpcMock: WARN ``` -------------------------------- ### Integrate JUnit 5 with GrpcMockExtension Source: https://github.com/fadelis/grpcmock/blob/master/README.md Use @ExtendWith to register the standard gRPC Mock extension for JUnit 5 tests. ```java @ExtendWith(GrpcMockExtension.class) class TestClass { private ManagedChannel channel; @BeforeEach void setupChannel() { channel = ManagedChannelBuilder.forAddress("localhost", GrpcMock.getGlobalPort()) .usePlaintext() .build(); } @AfterEach void shutdownChannel() { Optional.ofNullable(channel).ifPresent(ManagedChannel::shutdownNow); } } ``` -------------------------------- ### Stub Bidirectional Streaming Methods in Java Source: https://context7.com/fadelis/grpcmock/llms.txt Configure bidirectional streaming stubs using FunctionalResponseObserver to handle request-response cycles, including support for header matching and sequential scenarios. ```java import static org.grpcmock.GrpcMock.*; import org.grpcmock.util.FunctionalResponseObserver; // Basic bidi streaming with proxy response stubFor(bidiStreamingMethod(SimpleServiceGrpc.getBidiStreamingRpcMethod()) .willProxyTo(responseObserver -> FunctionalResponseObserver.builder() .onCompleted(() -> { responseObserver.onNext(response); responseObserver.onCompleted(); }) .build())); // Match on first request stubFor(bidiStreamingMethod(SimpleServiceGrpc.getBidiStreamingRpcMethod()) .withFirstRequest(req -> req.getRequestMessage().equals("start")) .willProxyTo(responseObserver -> FunctionalResponseObserver.builder() .onCompleted(() -> { responseObserver.onNext(response); responseObserver.onCompleted(); }) .build())); // Echo-style: respond to each incoming request stubFor(bidiStreamingMethod(SimpleServiceGrpc.getBidiStreamingRpcMethod()) .willProxyTo(responseObserver -> FunctionalResponseObserver.builder() .onNext(request -> { SimpleResponse echoResponse = SimpleResponse.newBuilder() .setResponseMessage("Echo: " + request.getRequestMessage()) .build(); responseObserver.onNext(echoResponse); }) .onCompleted(responseObserver::onCompleted) .build())); // Multiple different scenarios for successive calls stubFor(bidiStreamingMethod(SimpleServiceGrpc.getBidiStreamingRpcMethod()) .willProxyTo(firstScenarioObserver) .nextWillProxyTo(secondScenarioObserver)); // With header matching stubFor(bidiStreamingMethod(SimpleServiceGrpc.getBidiStreamingRpcMethod()) .withHeader("authorization", value -> value.startsWith("Bearer")) .willProxyTo(responseObserver -> FunctionalResponseObserver.builder() .onNext(request -> responseObserver.onNext(authenticatedResponse)) .onCompleted(responseObserver::onCompleted) .build())); ``` -------------------------------- ### Stub Unary gRPC Methods Source: https://github.com/fadelis/grpcmock/blob/master/README.md Configure responses for unary gRPC methods using matchers and optional delays. ```java stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response1)); stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .withHeader("header-1", "value-1") .withHeader("header-2", value -> value.startsWith("value")) .withRequest(expectedRequest) .willReturn(response(response1) .withFixedDelay(200)) // first invocation will return this response after 200 ms .nextWillReturn(response(response2))); // subsequent invocations will return this response ``` -------------------------------- ### Stub Server Streaming gRPC Methods Source: https://github.com/fadelis/grpcmock/blob/master/README.md Define sequences of responses for server streaming methods with optional delays and status exceptions. ```java stubFor(serverStreamingMethod(SimpleServiceGrpc.getServerStreamingRpcMethod()) .willReturn(responses1, responses2, responses3)); // return one by one with no delay stubFor(serverStreamingMethod(SimpleServiceGrpc.getServerStreamingRpcMethod()) .withHeader("header-1", "value-1") .withRequest(req -> req.getRequestMessage().endsWith("1")) .willReturn(stream(response(responses1).withFixedDelay(200)) .and(response(responses2).withFixedDelay(100)) .and(response(responses3).withFixedDelay(200))) .nextWillReturn(statusException(Status.NOT_FOUND))); // subsequent invocations will return status exception ``` -------------------------------- ### Verify gRPC Method Invocations Source: https://github.com/fadelis/grpcmock/blob/master/README.md Assert that specific gRPC methods were called with expected parameters and frequency. ```java verifyThat( calledMethod(getUnaryRpcMethod()) .withStatusOk() .withHeader("header-1", "value-1") .withRequest(request), times(3)); verifyThat(getUnaryRpcMethod(), never()); verifyThat( calledMethod(getClientStreamingRpcMethod()) .withNumberOfRequests(2) .withFirstRequest(request) .withRequestAtIndex(1, request2)); ``` -------------------------------- ### Stub Unary gRPC Methods Source: https://context7.com/fadelis/grpcmock/llms.txt Configure unary gRPC method responses using request matching, delays, error statuses, or dynamic logic. ```java import static org.grpcmock.GrpcMock.*; // Basic unary stub - returns response for any request stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response(SimpleResponse.newBuilder() .setResponseMessage("Hello World") .build()))); // Stub with request matching - only matches specific requests stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .withRequest(SimpleRequest.newBuilder().setRequestMessage("test").build()) .willReturn(response(expectedResponse))); // Stub with header matching stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .withHeader("authorization", "Bearer token123") .withHeader("x-request-id", value -> value.startsWith("req-")) .willReturn(response(expectedResponse))); // Stub with response delay (200ms) stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response(expectedResponse) .withFixedDelay(200))); // Stub with random delay (between 50-200ms) stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response(expectedResponse) .withRandomDelay(50, 200))); // Stub returning error status stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(statusException(Status.NOT_FOUND.withDescription("Resource not found")))); // Multiple sequential responses for successive calls stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(response(firstResponse)) .nextWillReturn(response(secondResponse)) .nextWillReturn(Status.INTERNAL)); // Dynamic response based on request stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willReturn(request -> SimpleResponse.newBuilder() .setResponseMessage("Echo: " + request.getRequestMessage()) .build())); // Proxy to custom implementation stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod()) .willProxyTo((request, responseObserver) -> { responseObserver.onNext(SimpleResponse.newBuilder() .setResponseMessage("Proxied: " + request.getRequestMessage()) .build()); responseObserver.onCompleted(); })); ``` -------------------------------- ### Stub Client Streaming gRPC Methods Source: https://github.com/fadelis/grpcmock/blob/master/README.md Stub client streaming methods based on the first request message received in the stream. ```java stubFor(clientStreamingMethod(SimpleServiceGrpc.getClientStreamingRpcMethod()) .willReturn(responses1)); // return a response on completed client streaming requests stubFor(clientStreamingMethod(SimpleServiceGrpc.getClientStreamingRpcMethod()) .withHeader("header-1", "value-1") .withFirstRequest(req -> req.getRequestMessage().endsWith("1")) .willReturn(response(responses1).withFixedDelay(200)) .nextWillReturn(statusException(Status.NOT_FOUND))); // subsequent invocations will return status exception ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.