Installation
composer require belsym/test-bundle
Add the bundle to config/bundles.php (Symfony only):
return [
// ...
Belsym\TestBundle\BelsymTestBundle::class => ['all' => true],
];
First Use Case
Extend MockedUpTestCase for basic mocking:
use Belsym\TestBundle\TestCase\MockedUpTestCase;
class MyTest extends MockedUpTestCase
{
public function testMockExample()
{
$mock = $this->mock('MyService');
$mock->shouldReceive('doSomething')->once();
// Test logic...
}
}
Key Files
src/TestCase/MockedUpTestCase.php (Base mocking)src/TestCase/MockContainerAwareTestCase.php (Mocked container + Doctrine)src/TestCase/ContainerAwareTestCase.php (Real Symfony container)Mocking Services
// In MockedUpTestCase
$mock = $this->mock('App\Service\MyService');
$mock->shouldReceive('process')->withArgs([1, 2])->andReturn(true);
Mocking Doctrine EntityManager
// In MockContainerAwareTestCase
$em = $this->createMockEntityManager();
$em->expects($this->once())->method('find')->with('User', 1)->willReturn(new User());
Real Container Integration (Symfony)
// In ContainerAwareTestCase
$service = $this->getContainer()->get('my.service');
MockedUpTestCase directly (Symfony-specific classes won’t work).MockedUpTestCase and override createApplication() to bind facades:
protected function createApplication()
{
$app = parent::createApplication();
$app->bind('App\Services\MyService', function () {
return $this->mock('App\Services\MyService');
});
}
MockedUpTestCase for unit tests; reserve ContainerAwareTestCase for integration tests.Symfony Dependency
ContainerAwareTestCase only works in Symfony. Throws RuntimeException if AppKernel is missing.MockContainerAwareTestCase for container-like behavior (but manually mock ContainerInterface).Mockery Initialization
MockedUpTestCase auto-loads Mockery, but ensure mockery/mockery is installed:
composer require --dev mockery/mockery
createMock()).Doctrine Mocking Quirks
createMockEntityManager() returns a partial mock. Override methods like persist() explicitly:
$em->expects($this->once())->method('persist')->with($user);
Mockery::close() in tearDown() to avoid memory leaks:
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
ContainerAwareTestCase, ensure APP_ENV=test and CACHE_DRIVER=array in .env.createMock() in MockedUpTestCase:
protected function createMock($originalClassName)
{
return Mockery::mock($originalClassName . '[doSomething]');
}
MockedUpTestCase and add helper methods:
class ApiTestCase extends MockedUpTestCase
{
protected function mockHttpClient()
{
return $this->mock('GuzzleHttp\Client', [
'request' => $this->mockResponse(200, ['data' => []])
]);
}
}
How can I help you explore Laravel packages today?