cerebrate/tests/Helper/WireMockTestTrait.php

92 lines
2.2 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace App\Test\Helper;
use \WireMock\Client\WireMock;
2022-01-27 15:43:33 +01:00
use \WireMock\Client\ValueMatchingStrategy;
use \WireMock\Client\RequestPatternBuilder;
use \WireMock\Stubbing\StubMapping;
trait WireMockTestTrait
{
/** @var WireMock */
private $wiremock;
/** @var array<mixed> */
2023-04-06 18:00:46 +02:00
private $config;
public function initializeWireMock(): void
{
2023-04-06 18:00:46 +02:00
$this->config = [
'hostname' => $_ENV['WIREMOCK_HOST'] ?? 'localhost',
'port' => $_ENV['WIREMOCK_PORT'] ?? 8080
];
$this->wiremock = WireMock::create(
2023-04-06 18:00:46 +02:00
$this->config['hostname'],
$this->config['port']
);
if (!$this->wiremock->isAlive()) {
2022-01-27 15:43:33 +01:00
throw new \Exception('Failed to connect to WireMock server.');
}
$this->clearWireMockStubs();
}
public function clearWireMockStubs(): void
{
$this->wiremock->resetToDefault();
}
public function getWireMock(): WireMock
{
return $this->wiremock;
}
public function getWireMockBaseUrl(): string
{
return sprintf('http://%s:%s', $this->config['hostname'], $this->config['port']);
}
2022-01-27 15:43:33 +01:00
/**
* Verify all WireMock stubs were called.
*
* @return void
*/
public function verifyAllStubsCalled(): void
{
$stubs = $this->wiremock->listAllStubMappings()->getMappings();
foreach ((array)$stubs as $stub) {
$this->verifyStubCalled($stub);
}
}
/**
* Verify the WireMock stub was called.
*
* @param StubMapping $stub
* @return void
*/
public function verifyStubCalled(StubMapping $stub): void
{
$validator = new RequestPatternBuilder($stub->getRequest()->getMethod(), $stub->getRequest()->getUrlMatchingStrategy());
// validate headers
$headers = $stub->getRequest()->getHeaders();
if (is_array($headers)) {
foreach ($headers as $header => $rule) {
$validator = $validator->withHeader($header, $rule);
2022-01-27 15:43:33 +01:00
}
}
// TODO: Add body matching
// TODO: Add query matching
// TODO: Add cookie matching
$this->wiremock->verify($validator);
}
}