<?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;
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']);
}
}