3 namespace Drupal\Tests\Component\Plugin\Discovery;
5 use PHPUnit\Framework\TestCase;
8 * @coversDefaultClass \Drupal\Component\Plugin\Discovery\DiscoveryCachedTrait
9 * @uses \Drupal\Component\Plugin\Discovery\DiscoveryTrait
12 class DiscoveryCachedTraitTest extends TestCase {
15 * Data provider for testGetDefinition().
18 * - Expected result from getDefinition().
19 * - Cached definitions to be placed into self::$definitions
20 * - Definitions to be returned by getDefinitions().
21 * - Plugin name to query for.
23 public function providerGetDefinition() {
25 ['definition', [], ['plugin_name' => 'definition'], 'plugin_name'],
26 ['definition', ['plugin_name' => 'definition'], [], 'plugin_name'],
27 [NULL, ['plugin_name' => 'definition'], [], 'bad_plugin_name'],
32 * @covers ::getDefinition
33 * @dataProvider providerGetDefinition
35 public function testGetDefinition($expected, $cached_definitions, $get_definitions, $plugin_id) {
36 // Mock a DiscoveryCachedTrait.
37 $trait = $this->getMockForTrait('Drupal\Component\Plugin\Discovery\DiscoveryCachedTrait');
38 $reflection_definitions = new \ReflectionProperty($trait, 'definitions');
39 $reflection_definitions->setAccessible(TRUE);
40 // getDefinition() needs the ::$definitions property to be set in one of two
41 // ways: 1) As existing cached data, or 2) as a side-effect of calling
43 // If there are no cached definitions, then we have to fake the side-effect
44 // of getDefinitions().
45 if (count($cached_definitions) < 1) {
46 $trait->expects($this->once())
47 ->method('getDefinitions')
48 // Use a callback method, so we can perform the side-effects.
49 ->willReturnCallback(function () use ($reflection_definitions, $trait, $get_definitions) {
50 $reflection_definitions->setValue($trait, $get_definitions);
51 return $get_definitions;
55 // Put $cached_definitions into our mocked ::$definitions.
56 $reflection_definitions->setValue($trait, $cached_definitions);
58 // Call getDefinition(), with $exception_on_invalid always FALSE.
61 $trait->getDefinition($plugin_id, FALSE)