function AllowedValuesConstraintValidatorTest::testValidation

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/TypedData/AllowedValuesConstraintValidatorTest.php \Drupal\KernelTests\Core\TypedData\AllowedValuesConstraintValidatorTest::testValidation()
  2. 8.9.x core/tests/Drupal/KernelTests/Core/TypedData/AllowedValuesConstraintValidatorTest.php \Drupal\KernelTests\Core\TypedData\AllowedValuesConstraintValidatorTest::testValidation()
  3. 10 core/tests/Drupal/KernelTests/Core/TypedData/AllowedValuesConstraintValidatorTest.php \Drupal\KernelTests\Core\TypedData\AllowedValuesConstraintValidatorTest::testValidation()

Tests the AllowedValues validation constraint validator.

For testing we define an integer with a set of allowed values.

File

core/tests/Drupal/KernelTests/Core/TypedData/AllowedValuesConstraintValidatorTest.php, line 38

Class

AllowedValuesConstraintValidatorTest
Tests AllowedValues validation constraint with both valid and invalid values.

Namespace

Drupal\KernelTests\Core\TypedData

Code

public function testValidation() : void {
    // Create a definition that specifies some AllowedValues.
    $definition = DataDefinition::create('integer')->addConstraint('AllowedValues', [
        1,
        2,
        3,
    ]);
    // Test the validation.
    $typed_data = $this->typedData
        ->create($definition, 1);
    $violations = $typed_data->validate();
    $this->assertEquals(0, $violations->count(), 'Validation passed for correct value.');
    // Test the validation when an invalid value is passed.
    $typed_data = $this->typedData
        ->create($definition, 4);
    $violations = $typed_data->validate();
    $this->assertEquals(1, $violations->count(), 'Validation failed for incorrect value.');
    // Make sure the information provided by a violation is correct.
    $violation = $violations[0];
    $this->assertEquals('The value you selected is not a valid choice.', $violation->getMessage(), 'The message for invalid value is correct.');
    $this->assertEquals($typed_data, $violation->getRoot(), 'Violation root is correct.');
    $this->assertEquals(4, $violation->getInvalidValue(), 'The invalid value is set correctly in the violation.');
    // Test the validation when a value of an incorrect type is passed.
    $typed_data = $this->typedData
        ->create($definition, '1');
    $violations = $typed_data->validate();
    $this->assertEquals(0, $violations->count(), 'Value is coerced to the correct type and is valid.');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.