Testing
composer test
# or
vendor/bin/phpunit
tests/
+-- Unit/
+-- ContainerTest.php
+-- DefinitionTest.php
+-- AutowiringTest.php
public function testBindAndResolve(): void
{
$container = new Container();
$container->bind('foo', fn() => 'bar');
$this->assertSame('bar', $container->get('foo'));
}
public function testSingletonReturnsSameInstance(): void
{
$container = new Container();
$container->singleton(stdClass::class, fn() => new stdClass());
$a = $container->get(stdClass::class);
$b = $container->get(stdClass::class);
$this->assertSame($a, $b);
}
public function testFactoryReturnsNewInstance(): void
{
$container = new Container();
$container->bind(stdClass::class, fn() => new stdClass());
$a = $container->get(stdClass::class);
$b = $container->get(stdClass::class);
$this->assertNotSame($a, $b);
}
class Dependency {}
class Consumer {
public function __construct(public Dependency $dep) {}
}
public function testAutowiring(): void
{
$container = new Container();
$consumer = $container->get(Consumer::class);
$this->assertInstanceOf(Consumer::class, $consumer);
$this->assertInstanceOf(Dependency::class, $consumer->dep);
}
public function testCircularDependencyThrows(): void
{
$container = new Container();
$container->bind('a', fn($c) => $c->get('b'));
$container->bind('b', fn($c) => $c->get('a'));
$this->expectException(ContainerException::class);
$this->expectExceptionMessage('Circular dependency');
$container->get('a');
}
public function testNotFoundThrows(): void
{
$container = new Container();
$this->expectException(NotFoundException::class);
$container->get('nonexistent');
}
public function testWithMockedDependency(): void
{
$container = new Container();
$mockLogger = $this->createMock(LoggerInterface::class);
$mockLogger->expects($this->once())->method('info');
$container->singleton(LoggerInterface::class, fn() => $mockLogger);
$service = $container->get(MyService::class);
$service->doSomething();
}