Package com.guinetik.rr
Class RocketRestMock
- java.lang.Object
-
- com.guinetik.rr.RocketRest
-
- com.guinetik.rr.RocketRestMock
-
public class RocketRestMock extends RocketRest
Mock implementation ofRocketRestfor 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 matchingSimulating 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
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class com.guinetik.rr.RocketRest
RocketRest.AsyncApi, RocketRest.FluentApi, RocketRest.SyncApi
-
-
Constructor Summary
Constructors Constructor Description RocketRestMock(RocketRestConfig config)Creates a new mock client instance.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description voidaddMockResponse(String method, String urlPattern, BiFunction<String,Object,Object> responseProducer)Adds a mock response for a specific HTTP method and exact URL match.voidaddMockResponse(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.RocketRest.AsyncApiasync()Provides a mock implementation for async API calls.<Req,Res>
Resexecute(RequestSpec<Req,Res> requestSpec)Executes a synchronous request with the given request specification.<Req,Res>
CompletableFuture<Res>executeAsync(RequestSpec<Req,Res> requestSpec)RocketRest.FluentApifluent()Provides a mock implementation for fluent API calls.intgetInvocationCount(String method, String urlPattern)Gets the number of times an endpoint was called.voidresetInvocationCounts()Resets all invocation counters.RocketRest.SyncApisync()Provides a mock implementation for sync API calls.voidwithLatency(String urlPatternRegex, long latencyMs)Adds simulated network latency for a specific URL pattern.-
Methods inherited from class com.guinetik.rr.RocketRest
configure, delete, get, get, getAccessToken, getTokenExpiryTime, post, post, put, put, setBaseUrl, shutdown
-
-
-
-
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 exactlyresponseProducer- 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 objectisRegexPattern- 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 URLslatencyMs- Delay in milliseconds
-
execute
public <Req,Res> Res execute(RequestSpec<Req,Res> requestSpec)
Description copied from class:RocketRestExecutes a synchronous request with the given request specification.- Overrides:
executein classRocketRest- Type Parameters:
Req- The request body typeRes- 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:
syncin classRocketRest- Returns:
- The synchronous API interface
-
async
public RocketRest.AsyncApi async()
Provides a mock implementation for async API calls.- Overrides:
asyncin classRocketRest- Returns:
- The asynchronous API interface
-
fluent
public RocketRest.FluentApi fluent()
Provides a mock implementation for fluent API calls.- Overrides:
fluentin classRocketRest- Returns:
- The fluent API interface
-
executeAsync
public <Req,Res> CompletableFuture<Res> executeAsync(RequestSpec<Req,Res> requestSpec)
-
-