rules-8.x-3.x-dev/tests/src/Unit/ContextHandlerTraitTest.php
tests/src/Unit/ContextHandlerTraitTest.php
<?php
declare(strict_types=1);
namespace Drupal\Tests\rules\Unit;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\rules\Context\ContextConfig;
use Drupal\rules\Context\ContextDefinitionInterface;
use Drupal\rules\Context\ContextHandlerTrait;
use Drupal\rules\Context\ExecutionStateInterface;
use Drupal\rules\Exception\EvaluationException;
// cspell:ignore testplugin
/**
* @coversDefaultClass \Drupal\rules\Context\ContextHandlerTrait
* @group Rules
*/
class ContextHandlerTraitTest extends RulesUnitTestBase {
/**
* Tests that a missing required context triggers an exception.
*
* @covers ::prepareContext
*/
public function testMissingContext(): void {
// Set the expected exception class and message.
$this->expectException(EvaluationException::class);
$this->expectExceptionMessage("Required context 'test' is missing for plugin 'testplugin'");
// Create an 'instance' of our trait.
$trait = new ContextHandlerTraitMockableClass();
$context_definition = $this->prophesize(ContextDefinitionInterface::class);
// Let the trait work with an empty configuration.
$trait->configuration = ContextConfig::create()->toArray();
// Make the context required in the definition.
$context_definition->isRequired()->willReturn(TRUE)->shouldBeCalledTimes(1);
$plugin = $this->prophesize(ContextAwarePluginInterface::class);
$plugin->getContextDefinitions()
->willReturn(['test' => $context_definition->reveal()])
->shouldBeCalled(1);
$plugin->getContextValue('test')
->willReturn(NULL)
->shouldBeCalled(1);
$plugin->getPluginId()->willReturn('testplugin')->shouldBeCalledTimes(1);
$state = $this->prophesize(ExecutionStateInterface::class);
// Make the 'prepareContext' method visible.
$reflection = new \ReflectionClass($trait);
$method = $reflection->getMethod('prepareContext');
$method->setAccessible(TRUE);
$method->invokeArgs($trait, [$plugin->reveal(), $state->reveal()]);
}
}
/**
* A class using the ContextHandlerTrait for mocking purposes.
*/
class ContextHandlerTraitMockableClass {
use ContextHandlerTrait;
/**
* The plugin configuration. Needed by the trait methods.
*
* @var array
*/
public $configuration;
}
