Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Plugin Mock Laravel Package

guzzle/plugin-mock

guzzle/plugin-mock provides a mock plugin for Guzzle, letting you queue predefined responses and simulate HTTP requests during testing. Useful for isolating API clients, reproducing edge cases, and running fast, reliable unit tests without real network calls.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require guzzle/plugin-mock:^3.0
    

    (Note: This is for Guzzle 3.x—ensure compatibility with your project.)

  2. Basic Mocking:

    use Guzzle\Plugin\Mock\MockPlugin;
    use Guzzle\Http\Message\RequestInterface;
    use Guzzle\Http\Message\Response;
    
    // Create a mock response
    $mockResponse = new Response(200, [], 'Mocked response');
    
    // Register the mock plugin
    $mock = new MockPlugin();
    $mock->addResponse($mockResponse);
    
    $client = new Guzzle\Http\Client();
    $client->addSubscriber($mock);
    
    // Test the mock
    $response = $client->get('http://example.com/api');
    echo $response->getBody(); // Outputs: "Mocked response"
    
  3. First Use Case:

    • Unit Testing: Replace external API calls with predictable responses.
    • Offline Development: Simulate API behavior without network requests.

Implementation Patterns

Common Workflows

  1. Chaining Responses:

    $mock->addResponse(new Response(200, [], 'First call'))
         ->addResponse(new Response(404, [], 'Second call'));
    
    • Useful for testing sequential API calls (e.g., pagination).
  2. Conditional Mocking:

    $mock->addResponse(
        new Response(200, [], 'Success'),
        'GET',
        '/api/users',
        ['headers' => ['Accept' => 'application/json']]
    );
    
    • Match requests by method, URI, and headers.
  3. Exception Simulation:

    $mock->addResponse(new \RuntimeException('API down'));
    
    • Test error handling in your application.
  4. Integration with Laravel:

    // In a test case
    $mock = new MockPlugin();
    $mock->addResponse(new Response(200, [], json_encode(['data' => 'test'])));
    
    $client = new GuzzleHttp\Client(['base_uri' => 'http://example.com']);
    $client->getEmitter()->getEmitter()->addSubscriber($mock);
    
    $response = $client->get('/api/endpoint');
    $this->assertEquals('test', json_decode($response->getBody())->data);
    

Best Practices

  • Isolate Mocks: Use separate mock instances per test to avoid cross-contamination.
  • Cleanup: Remove mocks after tests to avoid side effects in other tests.
  • Realistic Data: Mock responses should mirror real API structures (e.g., headers, status codes).

Gotchas and Tips

Pitfalls

  1. Guzzle 3 vs. 6+:

    • This package is for Guzzle 3.x. If using Guzzle 6/7, consider alternatives like php-mock-http or mockery.
    • Symptom: ClassNotFoundException for Guzzle\Http\Client.
  2. Case-Sensitive Matching:

    • URI matching in mocks is case-sensitive. Use lowercase URIs for consistency:
      $mock->addResponse($response, 'GET', '/api/Users'); // Fails if request is '/api/users'
      
  3. Subscriber Order:

    • Mocks must be added before other middleware (e.g., logging). Use addSubscriber() early in the chain.
  4. No Persistent State:

    • Mocks are stateless between requests. For stateful testing, use a custom mock class extending MockPlugin.

Debugging Tips

  • Verify Mocks:
    $mock->getResponses(); // Inspect registered responses.
    $mock->getRequestCount(); // Check how many times a mock was triggered.
    
  • Log Requests: Add a subscriber to log unmatched requests:
    $client->addSubscriber(new \Guzzle\Plugin\Log\LogPlugin());
    

Extension Points

  1. Custom Matchers: Extend MockPlugin to add dynamic matching logic:

    class CustomMockPlugin extends MockPlugin {
        public function addDynamicResponse(Closure $callback) {
            $this->responses[] = $callback;
        }
    }
    

    Usage:

    $mock->addDynamicResponse(function (RequestInterface $request) {
        return new Response(200, [], 'Dynamic: ' . $request->getUri());
    });
    
  2. Delay Simulation: Simulate network latency:

    $mock->addResponse(function () {
        sleep(2); // Simulate 2-second delay
        return new Response(200, [], 'Delayed response');
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky