docteurklein/test-double-bundle
Symfony bundle to simplify creating test doubles. Replace services automatically with stubs or fakes via DI container tags, improving test isolation and speed (e.g., Behat). Access original implementations with .real for infrastructure tests.
Installation:
composer require docteurklein/test-double-bundle --dev
Add the bundle only in test environments (e.g., config/bundles.php):
TestDoubleBundle\TestDoubleBundle::class => ['test' => true],
First Use Case:
Replace a service (e.g., GithubClient) with a stub for isolated testing.
Tag the service in its definition (e.g., src/Service/GuzzleClient.php):
use Doctrine\Common\Annotations\Tag;
/**
* @Service("github_client")
* @Tag("test_double", attributes={"stub"="GithubClient"})
*/
class GuzzleClient implements GithubClient { ... }
Access the Stub: Inject the prophecy service in your test context (e.g., Behat):
$this->getContainer()->get('github_client.prophecy')->method()->willReturn($mockValue);
Stubbing Services:
@Tag("test_double", attributes={"stub"="InterfaceName"}) to auto-generate a Prophecy stub.<service_id>.prophecy (e.g., github_client.prophecy).$this->container->get('http_client.prophecy')
->get('/api/issues')->willReturn(new Response(200, [], '{}'));
Faking Services:
@Tag("test_double", attributes={"fake"="service.fake"}).FakeGithubClient).// Fake service definition
$container->set('github_client.fake', FakeGithubClient::class);
Integration with Behat:
stub.prophet->checkPredictions() to verify interactions post-test..real suffix (e.g., github_client.real) for infrastructure tests.Final Classes: Stubbing fails if the original service is final (Prophecy limitation).
final.Service Overrides:
container.has('github_client.real') to verify original services exist.Prophecy Leaks:
checkPredictions().try-catch to fail fast:
try {
$this->container->get('stub.prophet')->checkPredictions();
} catch (\Prophecy\Exception\Exception $e) {
throw new \RuntimeException('Stub verification failed: ' . $e->getMessage());
}
Tag Attributes:
stub/fake attributes to auto-generate stubs for the service’s class.@Tag("test_double") → stubs GuzzleClient if the service implements GithubClient.Performance:
Extension Points:
DocteurKlein\TestDoubleBundle\DependencyInjection\Compiler\TestDoublePass.Debugging:
$this->container->get('debug:container')->dump();
.stub/.fake/.prophecy services.Legacy Code:
How can I help you explore Laravel packages today?