polishsymfonycommunity/symfony2-mocker-extension
Behat extension for Symfony2 that lets you mock services in the dependency injection container during tests. Built on Mockery and SymfonyMockerContainer. Consider it a hack and use sparingly; alternative: TestDoubleBundle.
Installation:
composer require polishsymfonycommunity/symfony2-mocker-extension
Add to behat.yml:
extensions:
PolishSymfonyCommunity\Symfony2MockerExtension\Extension: ~
First Use Case: Mock a service in a Behat context:
use Behat\Behat\Context\Context;
use PolishSymfonyCommunity\Symfony2MockerExtension\Context\MockerContext;
class FeatureContext implements Context, MockerContext {
public function mockService($serviceId, $mock) {
// Mockery mock object or closure
}
}
Key Files:
behat.yml (extension config)services.yml (for service IDs)Mocking Services in Contexts:
// In a Behat context
public function __construct() {
$this->mockService('app.mailer', function($mock) {
$mock->shouldReceive('send')
->once()
->with('test@example.com', 'Hello');
});
}
Partial Mocking:
$this->mockService('app.user_repository', function($mock) {
$mock->shouldReceive('findByEmail')
->andReturn(new User());
});
Integration with SymfonyMockerContainer:
// For complex scenarios, inject the container
public function __construct(SymfonyMockerContainer $container) {
$this->container = $container;
}
mockMailer()).->shouldReceive() instead of ->shouldIgnore() to avoid side effects.Service Not Found:
services.yml.dump($this->getServiceIds()) (if available).Mockery vs. PHPUnit:
shouldReceive() vs. expects()).Mockery::mock() for standalone mocks outside the container.Stateful Mocks:
$mock->shouldReceive('method')->andReturnNull()->byDefault();
$this->mockService('app.service', function($mock) {
$mock->shouldReceive('method')->andReturn('test');
// Later, verify:
$mock->shouldHaveReceived('method')->once();
});
$this->getContainer()->getServiceIds(); // List available services
Custom Mock Factories:
Override PolishSymfonyCommunity\Symfony2MockerExtension\MockFactory for reusable mock logic.
Event Listeners:
Attach to SymfonyMockerExtensionEvents (if extended):
$dispatcher->addListener('mock.service', function($event) { ... });
Legacy Code:
For Symfony 2.8+, consider migrating to TestDoubleBundle (as suggested in the README). This package is not maintained post-2016.
How can I help you explore Laravel packages today?