3 namespace Drupal\KernelTests\Core\TypedData;
5 use Drupal\Core\TypedData\DataDefinition;
6 use Drupal\KernelTests\KernelTestBase;
9 * Tests AllowedValues validation constraint with both valid and invalid values.
13 class AllowedValuesConstraintValidatorTest extends KernelTestBase {
16 * The typed data manager to use.
18 * @var \Drupal\Core\TypedData\TypedDataManager
22 protected function setUp() {
24 $this->typedData = $this->container->get('typed_data_manager');
28 * Tests the AllowedValues validation constraint validator.
30 * For testing we define an integer with a set of allowed values.
32 public function testValidation() {
33 // Create a definition that specifies some AllowedValues.
34 $definition = DataDefinition::create('integer')
35 ->addConstraint('AllowedValues', [1, 2, 3]);
37 // Test the validation.
38 $typed_data = $this->typedData->create($definition, 1);
39 $violations = $typed_data->validate();
40 $this->assertEqual($violations->count(), 0, 'Validation passed for correct value.');
42 // Test the validation when an invalid value is passed.
43 $typed_data = $this->typedData->create($definition, 4);
44 $violations = $typed_data->validate();
45 $this->assertEqual($violations->count(), 1, 'Validation failed for incorrect value.');
47 // Make sure the information provided by a violation is correct.
48 $violation = $violations[0];
49 $this->assertEqual($violation->getMessage(), t('The value you selected is not a valid choice.'), 'The message for invalid value is correct.');
50 $this->assertEqual($violation->getRoot(), $typed_data, 'Violation root is correct.');
51 $this->assertEqual($violation->getInvalidValue(), 4, 'The invalid value is set correctly in the violation.');