Class RocketRestMock


  • public class RocketRestMock
    extends RocketRest
    Mock implementation of RocketRest for unit testing without actual HTTP requests.

    This class simulates REST API interactions by returning predefined responses based on HTTP method and URL patterns. It supports regex matching, simulated network latency, invocation counting, and circuit breaker testing.

    Features

    • Predefined mock responses for any HTTP method and URL pattern
    • Regex-based URL matching for flexible endpoint simulation
    • Simulated network latency for timing-sensitive tests
    • Invocation counting for verification in tests
    • Circuit breaker integration for resilience testing

    Basic Usage

    
     // Create mock client
     RocketRestConfig config = RocketRestConfig.builder("https://api.example.com").build();
     RocketRestMock mockClient = new RocketRestMock(config);
    
     // Define mock responses
     mockClient.addMockResponse("GET", "/users/1", (url, body) -> {
         User user = new User();
         user.setId(1);
         user.setName("John Doe");
         return user;
     });
    
     // Use in tests
     User user = mockClient.get("/users/1", User.class);
     assertEquals("John Doe", user.getName());
     

    Regex URL Matching

    
     // Match any user ID (use regex pattern like /users/[0-9]+)
     mockClient.addMockResponse("GET", "/users/[0-9]+", (url, body) -> {
         // Extract ID from URL and return corresponding user
         String id = url.substring(url.lastIndexOf('/') + 1);
         User user = new User();
         user.setId(Integer.parseInt(id));
         return user;
     }, true);  // true enables regex matching
     

    Simulating Latency

    
     // Add 500ms latency for slow endpoint testing
     mockClient.withLatency("/slow-endpoint.*", 500L);
    
     // Test timeout behavior
     Result<Response, ApiError> result = mockClient.fluent()
         .get("/slow-endpoint", Response.class);
     

    Verifying Invocations

    
     // Make some calls
     mockClient.get("/users/1", User.class);
     mockClient.get("/users/1", User.class);
    
     // Verify call count
     assertEquals(2, mockClient.getInvocationCount("GET", "/users/1"));
    
     // Reset for next test
     mockClient.resetInvocationCounts();
     
    Since:
    1.0.0
    Author:
    guinetik <guinetik@gmail.com>
    See Also:
    RocketRest, MockRocketClient
    • Constructor Detail

      • RocketRestMock

        public RocketRestMock​(RocketRestConfig config)
        Creates a new mock client instance.
        Parameters:
        config - the configuration for the REST client
    • Method Detail

      • addMockResponse

        public void addMockResponse​(String method,
                                    String urlPattern,
                                    BiFunction<String,​Object,​Object> responseProducer)
        Adds a mock response for a specific HTTP method and exact URL match.
        Parameters:
        method - HTTP method (GET, POST, PUT, DELETE)
        urlPattern - URL pattern to match exactly
        responseProducer - Function that takes (url, requestBody) and returns a response object
      • addMockResponse

        public void addMockResponse​(String method,
                                    String urlPattern,
                                    BiFunction<String,​Object,​Object> responseProducer,
                                    boolean isRegexPattern)
        Adds a mock response with the option to use regex pattern matching for URLs.
        Parameters:
        method - HTTP method (GET, POST, PUT, DELETE)
        urlPattern - URL pattern (can be a regex pattern if isRegexPattern is true)
        responseProducer - Function that takes (url, requestBody) and returns a response object
        isRegexPattern - If true, the urlPattern will be treated as a regex pattern
      • getInvocationCount

        public int getInvocationCount​(String method,
                                      String urlPattern)
        Gets the number of times an endpoint was called.
        Parameters:
        method - HTTP method (GET, POST, PUT, DELETE)
        urlPattern - URL pattern or exact URL
        Returns:
        The number of invocations, or 0 if never called
      • resetInvocationCounts

        public void resetInvocationCounts()
        Resets all invocation counters.
      • withLatency

        public void withLatency​(String urlPatternRegex,
                                long latencyMs)
        Adds simulated network latency for a specific URL pattern.
        Parameters:
        urlPatternRegex - Regex pattern for matching URLs
        latencyMs - Delay in milliseconds
      • execute

        public <Req,​Res> Res execute​(RequestSpec<Req,​Res> requestSpec)
        Description copied from class: RocketRest
        Executes a synchronous request with the given request specification.
        Overrides:
        execute in class RocketRest
        Type Parameters:
        Req - The request body type
        Res - The response type
        Parameters:
        requestSpec - The request specification
        Returns:
        The response object
      • sync

        public RocketRest.SyncApi sync()
        Provides a mock implementation for sync API calls.
        Overrides:
        sync in class RocketRest
        Returns:
        The synchronous API interface
      • async

        public RocketRest.AsyncApi async()
        Provides a mock implementation for async API calls.
        Overrides:
        async in class RocketRest
        Returns:
        The asynchronous API interface