You are here

public function ContainerBuilderTest::testGet in Service Container 7

Same name and namespace in other branches
  1. 7.2 modules/providers/service_container_symfony/lib/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php \Symfony\Component\DependencyInjection\Tests\ContainerBuilderTest::testGet()

@covers Symfony\Component\DependencyInjection\ContainerBuilder::get

File

modules/providers/service_container_symfony/lib/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php, line 93

Class

ContainerBuilderTest

Namespace

Symfony\Component\DependencyInjection\Tests

Code

public function testGet() {
  $builder = new ContainerBuilder();
  try {
    $builder
      ->get('foo');
    $this
      ->fail('->get() throws an InvalidArgumentException if the service does not exist');
  } catch (\InvalidArgumentException $e) {
    $this
      ->assertEquals('The service definition "foo" does not exist.', $e
      ->getMessage(), '->get() throws an InvalidArgumentException if the service does not exist');
  }
  $this
    ->assertNull($builder
    ->get('foo', ContainerInterface::NULL_ON_INVALID_REFERENCE), '->get() returns null if the service does not exist and NULL_ON_INVALID_REFERENCE is passed as a second argument');
  $builder
    ->register('foo', 'stdClass');
  $this
    ->assertInternalType('object', $builder
    ->get('foo'), '->get() returns the service definition associated with the id');
  $builder
    ->set('bar', $bar = new \stdClass());
  $this
    ->assertEquals($bar, $builder
    ->get('bar'), '->get() returns the service associated with the id');
  $builder
    ->register('bar', 'stdClass');
  $this
    ->assertEquals($bar, $builder
    ->get('bar'), '->get() returns the service associated with the id even if a definition has been defined');
  $builder
    ->register('baz', 'stdClass')
    ->setArguments(array(
    new Reference('baz'),
  ));
  try {
    @$builder
      ->get('baz');
    $this
      ->fail('->get() throws a ServiceCircularReferenceException if the service has a circular reference to itself');
  } catch (\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException $e) {
    $this
      ->assertEquals('Circular reference detected for service "baz", path: "baz".', $e
      ->getMessage(), '->get() throws a LogicException if the service has a circular reference to itself');
  }
  $builder
    ->register('foobar', 'stdClass')
    ->setScope('container');
  $this
    ->assertTrue($builder
    ->get('bar') === $builder
    ->get('bar'), '->get() always returns the same instance if the service is shared');
}