3 namespace Drupal\Tests\Core\Plugin\Context;
5 use Drupal\Core\DependencyInjection\ContainerBuilder;
6 use Drupal\Core\Plugin\Context\Context;
7 use Drupal\Core\Plugin\Context\ContextDefinition;
8 use Drupal\Core\TypedData\DataDefinition;
9 use Drupal\Core\TypedData\Plugin\DataType\StringData;
10 use Drupal\Core\TypedData\TypedDataManagerInterface;
11 use Drupal\Tests\UnitTestCase;
14 * Tests that contexts work properly with the typed data manager.
16 * @coversDefaultClass \Drupal\Core\Plugin\Context\Context
19 class ContextTypedDataTest extends UnitTestCase {
22 * The typed data object used during testing.
24 * @var \Drupal\Core\TypedData\Plugin\DataType\StringData
29 * Tests that getting a context value does not throw fatal errors.
31 * This test ensures that the typed data manager is set correctly on the
34 * @covers ::getContextValue
36 public function testGetContextValue() {
37 // Prepare a container that holds the typed data manager mock.
38 $typed_data_manager = $this->getMock(TypedDataManagerInterface::class);
39 $typed_data_manager->expects($this->once())
40 ->method('getCanonicalRepresentation')
41 ->will($this->returnCallback([$this, 'getCanonicalRepresentation']));
42 $container = new ContainerBuilder();
43 $container->set('typed_data_manager', $typed_data_manager);
44 \Drupal::setContainer($container);
46 $definition = new ContextDefinition('any');
47 $data_definition = DataDefinition::create('string');
48 $this->typedData = new StringData($data_definition);
49 $this->typedData->setValue('example string');
50 $context = new Context($definition, $this->typedData);
51 $value = $context->getContextValue();
52 $this->assertSame($value, $this->typedData->getValue());
56 * Helper mock callback to return the typed data value.
58 public function getCanonicalRepresentation() {
59 return $this->typedData->getValue();