PHP code example of jasonbenett / codeception-module-wiremock

1. Go to this page and download the library: Download jasonbenett/codeception-module-wiremock library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jasonbenett / codeception-module-wiremock example snippets




class ApiTestCest
{
    public function testUserEndpoint(FunctionalTester $I)
    {
        // Create a stub for GET /api/users/1
        $I->haveHttpStubFor('GET', '/api/users/1', 200, [
            'id' => 1,
            'name' => 'John Doe',
            'email' => '[email protected]'
        ]);

        // Your application makes the HTTP request
        // ... your application code ...

        // Verify the request was made
        $I->seeHttpRequest('GET', '/api/users/1');
    }
}

// tests/_bootstrap.php or tests/_support/Helper/HttpClientProvider.php

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;

// Create PSR-18 HTTP Client
$httpClient = new Client([
    'timeout' => 10.0,
    'verify' => false,  // Disable SSL verification if needed
    'http_errors' => false,
]);

// Create PSR-17 factories (Guzzle's HttpFactory implements both interfaces)
$httpFactory = new HttpFactory();

// Store in global for Codeception access
$GLOBALS['wiremock_http_client'] = $httpClient;
$GLOBALS['wiremock_request_factory'] = $httpFactory;
$GLOBALS['wiremock_stream_factory'] = $httpFactory;

$stubId = $I->haveHttpStubFor(
    string $method,                // HTTP method (GET, POST, PUT, DELETE, etc.)
    string $url,                   // URL or URL pattern
    int $status = 200,             // HTTP status code
    $body = '',                    // Response body
    array $headers = [],           // Response headers
    array $requestMatchers = []    // Additional request matching criteria
): string;                         // Returns stub UUID

// Simple POST stub
$I->haveHttpStubFor('POST', '/api/users', 201, ['success' => true]);

// POST with body pattern matching
$I->haveHttpStubFor('POST', '/api/users', 201, ['created' => true], [], [
    'bodyPatterns' => [
        ['equalToJson' => ['name' => 'Jane Doe', 'email' => '[email protected]']]
    ]
]);

// PUT with header matching
$I->haveHttpStubFor('PUT', '/api/users/1', 200, ['updated' => true], [], [
    'headers' => [
        'Authorization' => [
            'matches' => 'Bearer .*'
        ]
    ]
]);

// DELETE with query parameters
$I->haveHttpStubFor('DELETE', '/api/users', 204, '', [], [
    'queryParameters' => [
        'id' => ['equalTo' => '123']
    ]
]);

$I->seeHttpRequest(
    string $method,                // HTTP method
    string $url,                   // URL or URL pattern
    array $additionalMatchers = [] // Additional matching criteria
): void;

// Basic verification
$I->seeHttpRequest('GET', '/api/users');

// With body verification
$I->seeHttpRequest('POST', '/api/users', [
    'bodyPatterns' => [
        ['contains' => '[email protected]']
    ]
]);

// With header verification
$I->seeHttpRequest('GET', '/api/data', [
    'headers' => [
        'Authorization' => ['matches' => 'Bearer .*']
    ]
]);

$I->dontSeeHttpRequest(
    string $method,                // HTTP method
    string $url,                   // URL or URL pattern
    array $additionalMatchers = [] // Additional matching criteria
): void;

// Verify endpoint was not called
$I->dontSeeHttpRequest('DELETE', '/api/users/1');

$I->seeRequestCount(
    int $expectedCount,       // Expected number of requests
    array $requestPattern     // Request matching pattern
): void;

// Verify exactly 3 requests
$I->seeRequestCount(3, ['method' => 'GET', 'url' => '/api/data']);

// Verify no requests to endpoint
$I->seeRequestCount(0, ['method' => 'DELETE', 'url' => '/api/users']);

$count = $I->grabRequestCount(
    array $requestPattern    // Request matching pattern
): int;

$count = $I->grabRequestCount(['method' => 'POST', 'url' => '/api/users']);
codecept_debug("Received {$count} POST requests");

$requests = $I->grabAllRequests(): array;

$requests = $I->grabAllRequests();
foreach ($requests as $request) {
    codecept_debug($request['method'] . ' ' . $request['url']);
}

$unmatched = $I->grabUnmatchedRequests(): array;

$unmatched = $I->grabUnmatchedRequests();
if (!empty($unmatched)) {
    codecept_debug('Unmatched requests:', $unmatched);
}

$I->sendReset(): void;

$I->sendClearRequests(): void;

// Exact match
['url' => '/exact/path']

// Regex pattern
['urlPattern' => '/api/users/.*']

// Path only (ignores query params)
['urlPath' => '/api/users']

// Path with regex
['urlPathPattern' => '/api/.*/items']

'bodyPatterns' => [
    ['equalTo' => 'exact string'],
    ['contains' => 'substring'],
    ['matches' => 'regex.*pattern'],
    ['equalToJson' => ['key' => 'value']],
    ['matchesJsonPath' => '$.store.book[?(@.price < 10)]'],
    ['equalToXml' => '<root>...</root>']
]

'headers' => [
    'Content-Type' => ['equalTo' => 'application/json'],
    'Authorization' => ['matches' => 'Bearer .*'],
    'X-Custom' => ['contains' => 'value']
]



class ShoppingCartCest
{
    public function testAddItemToCart(FunctionalTester $I)
    {
        // Setup: Create stub for adding item
        $I->haveHttpStubFor('POST', '/api/cart/items', 201,
            ['id' => 123, 'quantity' => 1],
            ['Content-Type' => 'application/json'],
            [
                'bodyPatterns' => [
                    ['matchesJsonPath' => '$.productId'],
                    ['matchesJsonPath' => '$.quantity']
                ]
            ]
        );

        // Setup: Create stub for getting cart
        $I->haveHttpStubFor('GET', '/api/cart', 200, [
            'items' => [
                ['id' => 123, 'productId' => 'PROD-1', 'quantity' => 1]
            ],
            'total' => 29.99
        ]);

        // Act: Your application code that interacts with the API
        // $cartService->addItem('PROD-1', 1);
        // $cart = $cartService->getCart();

        // Assert: Verify the expected requests were made
        $I->seeHttpRequest('POST', '/api/cart/items', [
            'bodyPatterns' => [
                ['matchesJsonPath' => '$.productId']
            ]
        ]);

        $I->seeHttpRequest('GET', '/api/cart');

        // Verify request count
        $I->seeRequestCount(1, ['method' => 'POST', 'url' => '/api/cart/items']);

        // Debug: Check all requests if needed
        $allRequests = $I->grabAllRequests();
        codecept_debug('Total requests made:', count($allRequests));
    }

    public function testEmptyCart(FunctionalTester $I)
    {
        // Verify no cart operations were performed
        $I->dontSeeHttpRequest('POST', '/api/cart/items');
        $I->dontSeeHttpRequest('GET', '/api/cart');
    }
}

$unmatched = $I->grabUnmatchedRequests();
if (!empty($unmatched)) {
    codecept_debug('These requests did not match any stub:');
    foreach ($unmatched as $request) {
        codecept_debug($request['method'] . ' ' . $request['url']);
    }
}

$allRequests = $I->grabAllRequests();
codecept_debug('All requests made:', $allRequests);
yaml
# codeception.yml or suite config
modules:
  enabled:
    - \JasonBenett\CodeceptionModuleWiremock\Module\Wiremock:
        host: 127.0.0.1
        port: 8080
        httpClient: !php/const GLOBALS['wiremock_http_client']
        requestFactory: !php/const GLOBALS['wiremock_request_factory']
        streamFactory: !php/const GLOBALS['wiremock_stream_factory']