Tuesday, 18 February 2025

How to Mock Twilio SDK Calls With Traffic Parrot

Current flow

RabbitMQ -> SpringBoot + Twilio SDK -> Twilio API

Desired flow with Traffic Parrot

RabbitMQ -> SpringBoot + Twilio SDK -> Traffic Parrot -> Twilio API

Details

  • Using Twilio REST API v2010
  • Endpoint: /Accounts/{account_sid}/Messages.json
  • OpenAPI spec: https://raw.githubusercontent.com/twilio/twilio-oai/main/spec/json/twilio_api_v2010.json

Question

How can we intercept and mock Twilio SDK calls using Traffic Parrot since the SDK doesn't accept a configurable URL?

Answer

Setup steps:

  1. Update your code to send requests to Traffic Parrot instead of real Twilio APIs, see sample code below
  2. Run Traffic Parrot on port 8081
  3. Configure recorder to forward requests to api.twilio.com
  4. Record sample responses from Twilio
  5. Switch recorder to replay mode
  6. Use the mock responses in your tests
// 1. Create a custom HTTP client that redirects Twilio requests to Traffic Parrot
public class TrafficParrotHttpClient extends NetworkHttpClient {
    private static final String TWILIO_API = "https://api.twilio.com";
    private static final String TRAFFIC_PARROT = "http://localhost:8081";
    
    @Override
    public Response makeRequest(Request request) {
        // Rewrite URL to point to Traffic Parrot
        String rewrittenUrl = request.getUrl().replace(TWILIO_API, TRAFFIC_PARROT);
        
        // Create new request with rewritten URL while preserving auth and other properties
        Request rewrittenRequest = new Request(request.getMethod(), rewrittenUrl)
            .setAuth(request.getUsername(), request.getPassword())
            .setHeaders(request.getHeaders());
            
        return super.makeRequest(rewrittenRequest);
    }
}

// 2. Configure Twilio client to use custom HTTP client
TwilioRestClient client = new TwilioRestClient.Builder("YOUR_ACCOUNT_SID", "YOUR_AUTH_TOKEN")
    .httpClient(new TrafficParrotHttpClient())
    .build();

// 3. Set as default client
Twilio.setRestClient(client);

// 4. Use Twilio SDK normally - calls will be redirected to Traffic Parrot
Message message = Message.creator(
    new PhoneNumber("+1555555555"),
    new PhoneNumber("+1555555556"), 
    "Hello from Traffic Parrot!")
    .create();

No comments:

Post a Comment