ServiceLocatorTest.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\DependencyInjection\Tests;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\DependencyInjection\ServiceLocator;
  13. class ServiceLocatorTest extends TestCase
  14. {
  15. public function testHas()
  16. {
  17. $locator = new ServiceLocator(array(
  18. 'foo' => function () { return 'bar'; },
  19. 'bar' => function () { return 'baz'; },
  20. function () { return 'dummy'; },
  21. ));
  22. $this->assertTrue($locator->has('foo'));
  23. $this->assertTrue($locator->has('bar'));
  24. $this->assertFalse($locator->has('dummy'));
  25. }
  26. public function testGet()
  27. {
  28. $locator = new ServiceLocator(array(
  29. 'foo' => function () { return 'bar'; },
  30. 'bar' => function () { return 'baz'; },
  31. ));
  32. $this->assertSame('bar', $locator->get('foo'));
  33. $this->assertSame('baz', $locator->get('bar'));
  34. }
  35. public function testGetDoesNotMemoize()
  36. {
  37. $i = 0;
  38. $locator = new ServiceLocator(array(
  39. 'foo' => function () use (&$i) {
  40. ++$i;
  41. return 'bar';
  42. },
  43. ));
  44. $this->assertSame('bar', $locator->get('foo'));
  45. $this->assertSame('bar', $locator->get('foo'));
  46. $this->assertSame(2, $i);
  47. }
  48. /**
  49. * @expectedException \Psr\Container\NotFoundExceptionInterface
  50. * @expectedExceptionMessage You have requested a non-existent service "dummy"
  51. */
  52. public function testGetThrowsOnUndefinedService()
  53. {
  54. $locator = new ServiceLocator(array(
  55. 'foo' => function () { return 'bar'; },
  56. 'bar' => function () { return 'baz'; },
  57. ));
  58. $locator->get('dummy');
  59. }
  60. public function testInvoke()
  61. {
  62. $locator = new ServiceLocator(array(
  63. 'foo' => function () { return 'bar'; },
  64. 'bar' => function () { return 'baz'; },
  65. ));
  66. $this->assertSame('bar', $locator('foo'));
  67. $this->assertSame('baz', $locator('bar'));
  68. $this->assertNull($locator('dummy'), '->__invoke() should return null on invalid service');
  69. }
  70. }