matthiasnoback/phpunit-test-service-container
composer require --dev matthiasnoback/phpunit-test-service-container
use MatthiasNoback\PHPUnitTestServiceContainer\TestCase;
class MyTest extends TestCase
{
// Your tests here
}
use MatthiasNoback\PHPUnitTestServiceContainer\ServiceProviderInterface;
use Pimple\Container;
use Pimple\ServiceProviderInterface as PimpleServiceProviderInterface;
class MyServiceProvider implements ServiceProviderInterface
{
public function register(Container $container)
{
$container['my_service'] = function () {
return new MyService();
};
}
}
protected function getServiceProviders()
{
return [
MyServiceProvider::class,
];
}
public function testSomething()
{
$service = $this->getService('my_service');
// Use $service in assertions
}
Mock external dependencies (e.g., databases, APIs) by registering mock implementations in providers. Example:
class DatabaseServiceProvider implements ServiceProviderInterface
{
public function register(Container $container)
{
$container['db'] = function () {
return $this->createMock(Database::class);
};
}
}
Isolated Test Dependencies:
$container['http_client'] = function () {
return $this->createMock(GuzzleClient::class);
};
Shared Test State:
$container['test_user'] = function () {
return User::factory()->create(['name' => 'Test User']);
};
Dependency Chaining:
$container['user_repository'] = function ($c) {
return new UserRepository($c['db'], $c['test_user']);
};
Dynamic Service Resolution:
$container['expensive_service'] = function () {
return new ExpensiveService(config('test.expensive_config'));
};
$container['app'] = function ($c) {
$app = new Illuminate\Foundation\Application();
$app->bind('db', function () use ($c) {
return $c['db']; // Your mock DB
});
return $app;
};
$container['config'] = function () {
return require __DIR__.'/test_config.php';
};
UserTestProvider, PaymentTestProvider) for modularity.Service Overrides:
Circular Dependencies:
container->offsetExists() to check for existing services before binding.Stateful Services:
setUp():
public function setUp(): void
{
$this->getService('stateful_service')->reset();
}
Provider Order:
getServiceProviders(). Depend on explicit ordering or use dependency injection within providers.$this->getContainer()->keys(); // List all registered services
$this->getContainer()->offsetGet('service_name'); // Inspect a service
$container->debug = true; // Logs service resolution
Custom Base Test Case:
TestCase to add default providers or pre-configured services:
class BaseTest extends TestCase
{
protected function getServiceProviders()
{
return [
CommonTestProvider::class,
parent::getServiceProviders(),
];
}
}
Dynamic Providers:
protected function getServiceProviders()
{
return array_merge(
[CommonProvider::class],
$this->shouldUseSpecialProvider() ? [SpecialProvider::class] : []
);
}
Service Factories:
$container['user_factory'] = function () {
return User::factory();
};
offsetGet vs get).How can I help you explore Laravel packages today?