3 namespace Drupal\Tests\rest\Unit;
5 use Drupal\Core\Entity\EntityConstraintViolationList;
6 use Drupal\node\Entity\Node;
7 use Drupal\Tests\UnitTestCase;
8 use Drupal\user\Entity\User;
9 use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
10 use Symfony\Component\Validator\ConstraintViolationInterface;
14 * @coversDefaultClass \Drupal\rest\Plugin\rest\resource\EntityResourceValidationTrait
16 class EntityResourceValidationTraitTest extends UnitTestCase {
21 public function testValidate() {
22 $trait = $this->getMockForTrait('Drupal\rest\Plugin\rest\resource\EntityResourceValidationTrait');
24 $method = new \ReflectionMethod($trait, 'validate');
25 $method->setAccessible(TRUE);
27 $violations = $this->prophesize(EntityConstraintViolationList::class);
28 $violations->filterByFieldAccess()->shouldBeCalled()->willReturn([]);
29 $violations->count()->shouldBeCalled()->willReturn(0);
31 $entity = $this->prophesize(Node::class);
32 $entity->validate()->shouldBeCalled()->willReturn($violations->reveal());
34 $method->invoke($trait, $entity->reveal());
40 public function testFailedValidate() {
41 $violation1 = $this->prophesize(ConstraintViolationInterface::class);
42 $violation1->getPropertyPath()->willReturn('property_path');
43 $violation1->getMessage()->willReturn('message');
45 $violation2 = $this->prophesize(ConstraintViolationInterface::class);
46 $violation2->getPropertyPath()->willReturn('property_path');
47 $violation2->getMessage()->willReturn('message');
49 $entity = $this->prophesize(User::class);
51 $violations = $this->getMockBuilder(EntityConstraintViolationList::class)
52 ->setConstructorArgs([$entity->reveal(), [$violation1->reveal(), $violation2->reveal()]])
53 ->setMethods(['filterByFieldAccess'])
56 $violations->expects($this->once())
57 ->method('filterByFieldAccess')
58 ->will($this->returnValue([]));
60 $entity->validate()->willReturn($violations);
62 $trait = $this->getMockForTrait('Drupal\rest\Plugin\rest\resource\EntityResourceValidationTrait');
64 $method = new \ReflectionMethod($trait, 'validate');
65 $method->setAccessible(TRUE);
67 $this->setExpectedException(UnprocessableEntityHttpException::class);
69 $method->invoke($trait, $entity->reveal());