diff --git a/src/Symfony/Bridge/Doctrine/Tests/DataCollector/DoctrineDataCollectorTest.php b/src/Symfony/Bridge/Doctrine/Tests/DataCollector/DoctrineDataCollectorTest.php index b1299c46a17e..9c31d6d7e76b 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DataCollector/DoctrineDataCollectorTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DataCollector/DoctrineDataCollectorTest.php @@ -11,6 +11,7 @@ namespace Symfony\Bridge\Doctrine\Tests\DataCollector; +use Doctrine\DBAL\Logging\DebugStack; use Doctrine\DBAL\Platforms\MySqlPlatform; use Doctrine\DBAL\Version; use Doctrine\Persistence\ManagerRegistry; @@ -236,7 +237,7 @@ private function createCollector($queries) ->method('getDatabasePlatform') ->willReturn(new MySqlPlatform()); - $registry = $this->getMockBuilder(ManagerRegistry::class)->getMock(); + $registry = $this->createMock(ManagerRegistry::class); $registry ->expects($this->any()) ->method('getConnectionNames') @@ -249,7 +250,7 @@ private function createCollector($queries) ->method('getConnection') ->willReturn($connection); - $logger = $this->getMockBuilder(\Doctrine\DBAL\Logging\DebugStack::class)->getMock(); + $logger = $this->createMock(DebugStack::class); $logger->queries = $queries; $collector = new DoctrineDataCollector($registry); diff --git a/src/Symfony/Bridge/Doctrine/Tests/DataFixtures/ContainerAwareLoaderTest.php b/src/Symfony/Bridge/Doctrine/Tests/DataFixtures/ContainerAwareLoaderTest.php index 94c9f0c54dc9..dd7a63fea468 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DataFixtures/ContainerAwareLoaderTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DataFixtures/ContainerAwareLoaderTest.php @@ -14,12 +14,13 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader; use Symfony\Bridge\Doctrine\Tests\Fixtures\ContainerAwareFixture; +use Symfony\Component\DependencyInjection\ContainerInterface; class ContainerAwareLoaderTest extends TestCase { public function testShouldSetContainerOnContainerAwareFixture() { - $container = $this->getMockBuilder(\Symfony\Component\DependencyInjection\ContainerInterface::class)->getMock(); + $container = $this->createMock(ContainerInterface::class); $loader = new ContainerAwareLoader($container); $fixture = new ContainerAwareFixture(); diff --git a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php index 7d3149f5cd8b..4fb8a0a4437d 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php @@ -12,6 +12,7 @@ namespace Symfony\Bridge\Doctrine\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\Doctrine\DependencyInjection\AbstractDoctrineExtension; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; @@ -22,7 +23,7 @@ class DoctrineExtensionTest extends TestCase { /** - * @var \Symfony\Bridge\Doctrine\DependencyInjection\AbstractDoctrineExtension + * @var AbstractDoctrineExtension */ private $extension; @@ -31,7 +32,7 @@ protected function setUp(): void parent::setUp(); $this->extension = $this - ->getMockBuilder(\Symfony\Bridge\Doctrine\DependencyInjection\AbstractDoctrineExtension::class) + ->getMockBuilder(AbstractDoctrineExtension::class) ->setMethods([ 'getMappingResourceConfigDirectory', 'getObjectManagerElementName', diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php index 67e9f8a625f4..afe595c7d3e1 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php @@ -75,19 +75,17 @@ class DoctrineChoiceLoaderTest extends TestCase protected function setUp(): void { - $this->factory = $this->getMockBuilder(ChoiceListFactoryInterface::class)->getMock(); - $this->om = $this->getMockBuilder(ObjectManager::class)->getMock(); - $this->repository = $this->getMockBuilder(ObjectRepository::class)->getMock(); + $this->factory = $this->createMock(ChoiceListFactoryInterface::class); + $this->om = $this->createMock(ObjectManager::class); + $this->repository = $this->createMock(ObjectRepository::class); $this->class = 'stdClass'; - $this->idReader = $this->getMockBuilder(IdReader::class) - ->disableOriginalConstructor() - ->getMock(); + $this->idReader = $this->createMock(IdReader::class); $this->idReader->expects($this->any()) ->method('isSingleId') ->willReturn(true) ; - $this->objectLoader = $this->getMockBuilder(EntityLoaderInterface::class)->getMock(); + $this->objectLoader = $this->createMock(EntityLoaderInterface::class); $this->obj1 = (object) ['name' => 'A']; $this->obj2 = (object) ['name' => 'B']; $this->obj3 = (object) ['name' => 'C']; diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/DataTransformer/CollectionToArrayTransformerTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/DataTransformer/CollectionToArrayTransformerTest.php index 4ecd501d3ea7..48470c607db8 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/DataTransformer/CollectionToArrayTransformerTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/DataTransformer/CollectionToArrayTransformerTest.php @@ -14,6 +14,7 @@ use Doctrine\Common\Collections\ArrayCollection; use PHPUnit\Framework\TestCase; use Symfony\Bridge\Doctrine\Form\DataTransformer\CollectionToArrayTransformer; +use Symfony\Component\Form\Exception\TransformationFailedException; /** * @author Bernhard Schussek @@ -64,7 +65,7 @@ public function testTransformNull() public function testTransformExpectsArrayOrCollection() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->transformer->transform('Foo'); } diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/DoctrineOrmTypeGuesserTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/DoctrineOrmTypeGuesserTest.php index 79ea8a188589..e003a20ee6b5 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/DoctrineOrmTypeGuesserTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/DoctrineOrmTypeGuesserTest.php @@ -34,21 +34,21 @@ public function requiredProvider() $return = []; // Simple field, not nullable - $classMetadata = $this->getMockBuilder(ClassMetadata::class)->disableOriginalConstructor()->getMock(); + $classMetadata = $this->createMock(ClassMetadata::class); $classMetadata->fieldMappings['field'] = true; $classMetadata->expects($this->once())->method('isNullable')->with('field')->willReturn(false); $return[] = [$classMetadata, new ValueGuess(true, Guess::HIGH_CONFIDENCE)]; // Simple field, nullable - $classMetadata = $this->getMockBuilder(ClassMetadata::class)->disableOriginalConstructor()->getMock(); + $classMetadata = $this->createMock(ClassMetadata::class); $classMetadata->fieldMappings['field'] = true; $classMetadata->expects($this->once())->method('isNullable')->with('field')->willReturn(true); $return[] = [$classMetadata, new ValueGuess(false, Guess::MEDIUM_CONFIDENCE)]; // One-to-one, nullable (by default) - $classMetadata = $this->getMockBuilder(ClassMetadata::class)->disableOriginalConstructor()->getMock(); + $classMetadata = $this->createMock(ClassMetadata::class); $classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->willReturn(true); $mapping = ['joinColumns' => [[]]]; @@ -57,7 +57,7 @@ public function requiredProvider() $return[] = [$classMetadata, new ValueGuess(false, Guess::HIGH_CONFIDENCE)]; // One-to-one, nullable (explicit) - $classMetadata = $this->getMockBuilder(ClassMetadata::class)->disableOriginalConstructor()->getMock(); + $classMetadata = $this->createMock(ClassMetadata::class); $classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->willReturn(true); $mapping = ['joinColumns' => [['nullable' => true]]]; @@ -66,7 +66,7 @@ public function requiredProvider() $return[] = [$classMetadata, new ValueGuess(false, Guess::HIGH_CONFIDENCE)]; // One-to-one, not nullable - $classMetadata = $this->getMockBuilder(ClassMetadata::class)->disableOriginalConstructor()->getMock(); + $classMetadata = $this->createMock(ClassMetadata::class); $classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->willReturn(true); $mapping = ['joinColumns' => [['nullable' => false]]]; @@ -75,7 +75,7 @@ public function requiredProvider() $return[] = [$classMetadata, new ValueGuess(true, Guess::HIGH_CONFIDENCE)]; // One-to-many, no clue - $classMetadata = $this->getMockBuilder(ClassMetadata::class)->disableOriginalConstructor()->getMock(); + $classMetadata = $this->createMock(ClassMetadata::class); $classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->willReturn(false); $return[] = [$classMetadata, null]; @@ -85,10 +85,10 @@ public function requiredProvider() private function getGuesser(ClassMetadata $classMetadata) { - $em = $this->getMockBuilder(ObjectManager::class)->getMock(); + $em = $this->createMock(ObjectManager::class); $em->expects($this->once())->method('getClassMetaData')->with('TestEntity')->willReturn($classMetadata); - $registry = $this->getMockBuilder(ManagerRegistry::class)->getMock(); + $registry = $this->createMock(ManagerRegistry::class); $registry->expects($this->once())->method('getManagers')->willReturn([$em]); return new DoctrineOrmTypeGuesser($registry); diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/EventListener/MergeDoctrineCollectionListenerTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/EventListener/MergeDoctrineCollectionListenerTest.php index 22692eea43ed..bbc69237ff36 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/EventListener/MergeDoctrineCollectionListenerTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/EventListener/MergeDoctrineCollectionListenerTest.php @@ -18,6 +18,7 @@ use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; +use Symfony\Component\Form\FormFactoryInterface; class MergeDoctrineCollectionListenerTest extends TestCase { @@ -32,7 +33,7 @@ protected function setUp(): void { $this->collection = new ArrayCollection(['test']); $this->dispatcher = new EventDispatcher(); - $this->factory = $this->getMockBuilder(\Symfony\Component\Form\FormFactoryInterface::class)->getMock(); + $this->factory = $this->createMock(FormFactoryInterface::class); $this->form = $this->getBuilder() ->getForm(); } diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypePerformanceTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypePerformanceTest.php index 33e6a6fd8723..42c0c5fb8c63 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypePerformanceTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypePerformanceTest.php @@ -35,7 +35,7 @@ class EntityTypePerformanceTest extends FormPerformanceTestCase protected function getExtensions() { - $manager = $this->getMockBuilder(ManagerRegistry::class)->getMock(); + $manager = $this->createMock(ManagerRegistry::class); $manager->expects($this->any()) ->method('getManager') diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php index e7ce4b3ecf81..d082ba5492b1 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php @@ -29,11 +29,16 @@ use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdNoToStringEntity; use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringCastableIdEntity; use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity; +use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface; use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView; use Symfony\Component\Form\ChoiceList\View\ChoiceView; +use Symfony\Component\Form\Exception\RuntimeException; +use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Forms; use Symfony\Component\Form\Tests\Extension\Core\Type\BaseTypeTest; use Symfony\Component\Form\Tests\Extension\Core\Type\FormTypeTest; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\Exception\MissingOptionsException; class EntityTypeTest extends BaseTypeTest { @@ -118,13 +123,13 @@ protected function persist(array $entities) public function testClassOptionIsRequired() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\MissingOptionsException::class); + $this->expectException(MissingOptionsException::class); $this->factory->createNamed('name', static::TESTED_TYPE); } public function testInvalidClassOption() { - $this->expectException(\Symfony\Component\Form\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->factory->createNamed('name', static::TESTED_TYPE, null, [ 'class' => 'foo', ]); @@ -219,7 +224,7 @@ public function testSetDataToUninitializedEntityWithNonRequiredQueryBuilder() public function testConfigureQueryBuilderWithNonQueryBuilderAndNonClosure() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->createNamed('name', static::TESTED_TYPE, null, [ 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, @@ -229,7 +234,7 @@ public function testConfigureQueryBuilderWithNonQueryBuilderAndNonClosure() public function testConfigureQueryBuilderWithClosureReturningNonQueryBuilder() { - $this->expectException(\Symfony\Component\Form\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $field = $this->factory->createNamed('name', static::TESTED_TYPE, null, [ 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, @@ -1242,7 +1247,7 @@ public function testLoaderCaching() $choiceLoader2 = $form->get('property2')->getConfig()->getOption('choice_loader'); $choiceLoader3 = $form->get('property3')->getConfig()->getOption('choice_loader'); - $this->assertInstanceOf(\Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface::class, $choiceLoader1); + $this->assertInstanceOf(ChoiceLoaderInterface::class, $choiceLoader1); $this->assertSame($choiceLoader1, $choiceLoader2); $this->assertSame($choiceLoader1, $choiceLoader3); } @@ -1302,14 +1307,14 @@ public function testLoaderCachingWithParameters() $choiceLoader2 = $form->get('property2')->getConfig()->getOption('choice_loader'); $choiceLoader3 = $form->get('property3')->getConfig()->getOption('choice_loader'); - $this->assertInstanceOf(\Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface::class, $choiceLoader1); + $this->assertInstanceOf(ChoiceLoaderInterface::class, $choiceLoader1); $this->assertSame($choiceLoader1, $choiceLoader2); $this->assertSame($choiceLoader1, $choiceLoader3); } protected function createRegistryMock($name, $em) { - $registry = $this->getMockBuilder(ManagerRegistry::class)->getMock(); + $registry = $this->createMock(ManagerRegistry::class); $registry->expects($this->any()) ->method('getManager') ->with($this->equalTo($name)) diff --git a/src/Symfony/Bridge/Doctrine/Tests/Logger/DbalLoggerTest.php b/src/Symfony/Bridge/Doctrine/Tests/Logger/DbalLoggerTest.php index 786ed1b22cae..d79b7d499813 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Logger/DbalLoggerTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Logger/DbalLoggerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Bridge\Doctrine\Tests\Logger; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; use Symfony\Bridge\Doctrine\Logger\DbalLogger; class DbalLoggerTest extends TestCase @@ -21,7 +22,7 @@ class DbalLoggerTest extends TestCase */ public function testLog($sql, $params, $logParams) { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $dbalLogger = $this ->getMockBuilder(DbalLogger::class) @@ -53,7 +54,7 @@ public function getLogFixtures() public function testLogNonUtf8() { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $dbalLogger = $this ->getMockBuilder(DbalLogger::class) @@ -76,7 +77,7 @@ public function testLogNonUtf8() public function testLogNonUtf8Array() { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $dbalLogger = $this ->getMockBuilder(DbalLogger::class) @@ -107,7 +108,7 @@ public function testLogNonUtf8Array() public function testLogLongString() { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $dbalLogger = $this ->getMockBuilder(DbalLogger::class) @@ -135,7 +136,7 @@ public function testLogLongString() public function testLogUTF8LongString() { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $dbalLogger = $this ->getMockBuilder(DbalLogger::class) diff --git a/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php b/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php index e0cfa0774868..49914454569e 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php @@ -11,6 +11,7 @@ namespace Symfony\Bridge\Doctrine\Tests\Security\User; +use Doctrine\ORM\EntityManager; use Doctrine\ORM\Tools\SchemaTool; use Doctrine\Persistence\ManagerRegistry; use Doctrine\Persistence\ObjectManager; @@ -20,6 +21,7 @@ use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface; use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper; use Symfony\Bridge\Doctrine\Tests\Fixtures\User; +use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\User\PasswordUpgraderInterface; use Symfony\Component\Security\Core\User\UserInterface; @@ -71,9 +73,7 @@ public function testLoadUserByUsernameWithUserLoaderRepositoryAndWithoutProperty ->with('user1') ->willReturn($user); - $em = $this->getMockBuilder(\Doctrine\ORM\EntityManager::class) - ->disableOriginalConstructor() - ->getMock(); + $em = $this->createMock(EntityManager::class); $em ->expects($this->once()) ->method('getRepository') @@ -125,7 +125,7 @@ public function testRefreshInvalidUser() $provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User', 'name'); $user2 = new User(1, 2, 'user2'); - $this->expectException(\Symfony\Component\Security\Core\Exception\UsernameNotFoundException::class); + $this->expectException(UsernameNotFoundException::class); $this->expectExceptionMessage('User with id {"id1":1,"id2":2} not found'); $provider->refreshUser($user2); @@ -155,7 +155,7 @@ public function testLoadUserByUserNameShouldLoadUserWhenProperInterfaceProvided( ->method('loadUserByUsername') ->with('name') ->willReturn( - $this->getMockBuilder(UserInterface::class)->getMock() + $this->createMock(UserInterface::class) ); $provider = new EntityUserProvider( @@ -198,7 +198,7 @@ public function testPasswordUpgrades() private function getManager($em, $name = null) { - $manager = $this->getMockBuilder(ManagerRegistry::class)->getMock(); + $manager = $this->createMock(ManagerRegistry::class); $manager->expects($this->any()) ->method('getManager') ->with($this->equalTo($name)) diff --git a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php index 4aee8ff91103..d8b7abc8064b 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php @@ -22,6 +22,7 @@ use Symfony\Bridge\Doctrine\Test\TestRepositoryFactory; use Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity; use Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity2; +use Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity; use Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeObjectNoToStringIdEntity; use Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity; use Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNullableNameEntity; @@ -30,9 +31,12 @@ use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity; use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdNoToStringEntity; use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdStringWrapperNameEntity; +use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity; use Symfony\Bridge\Doctrine\Tests\Fixtures\Type\StringWrapper; +use Symfony\Bridge\Doctrine\Tests\Fixtures\Type\StringWrapperType; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; /** @@ -67,7 +71,7 @@ protected function setUp(): void $config->setRepositoryFactory($this->repositoryFactory); if (!Type::hasType('string_wrapper')) { - Type::addType('string_wrapper', 'Symfony\Bridge\Doctrine\Tests\Fixtures\Type\StringWrapperType'); + Type::addType('string_wrapper', StringWrapperType::class); } $this->em = DoctrineTestHelper::createTestEntityManager($config); @@ -79,7 +83,7 @@ protected function setUp(): void protected function createRegistryMock($em = null) { - $registry = $this->getMockBuilder(ManagerRegistry::class)->getMock(); + $registry = $this->createMock(ManagerRegistry::class); $registry->expects($this->any()) ->method('getManager') ->with($this->equalTo(self::EM_NAME)) @@ -100,15 +104,13 @@ protected function createRepositoryMock() protected function createEntityManagerMock($repositoryMock) { - $em = $this->getMockBuilder(ObjectManager::class) - ->getMock() - ; + $em = $this->createMock(ObjectManager::class); $em->expects($this->any()) ->method('getRepository') ->willReturn($repositoryMock) ; - $classMetadata = $this->getMockBuilder(ClassMetadata::class)->getMock(); + $classMetadata = $this->createMock(ClassMetadata::class); $classMetadata ->expects($this->any()) ->method('hasField') @@ -137,17 +139,17 @@ private function createSchema($em) { $schemaTool = new SchemaTool($em); $schemaTool->createSchema([ - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdNoToStringEntity'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNullableNameEntity'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity2'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\Person'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\Employee'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeObjectNoToStringIdEntity'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdStringWrapperNameEntity'), + $em->getClassMetadata(SingleIntIdEntity::class), + $em->getClassMetadata(SingleIntIdNoToStringEntity::class), + $em->getClassMetadata(DoubleNameEntity::class), + $em->getClassMetadata(DoubleNullableNameEntity::class), + $em->getClassMetadata(CompositeIntIdEntity::class), + $em->getClassMetadata(AssociationEntity::class), + $em->getClassMetadata(AssociationEntity2::class), + $em->getClassMetadata(Person::class), + $em->getClassMetadata(Employee::class), + $em->getClassMetadata(CompositeObjectNoToStringIdEntity::class), + $em->getClassMetadata(SingleIntIdStringWrapperNameEntity::class), ]); } @@ -269,7 +271,7 @@ public function testValidateUniquenessWithIgnoreNullDisabled() public function testAllConfiguredFieldsAreCheckedOfBeingMappedByDoctrineWithIgnoreNullEnabled() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $constraint = new UniqueEntity([ 'message' => 'myMessage', 'fields' => ['name', 'name2'], @@ -540,7 +542,7 @@ public function testAssociatedEntityWithNull() public function testValidateUniquenessWithArrayValue() { $repository = $this->createRepositoryMock(); - $this->repositoryFactory->setRepository($this->em, 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', $repository); + $this->repositoryFactory->setRepository($this->em, SingleIntIdEntity::class, $repository); $constraint = new UniqueEntity([ 'message' => 'myMessage', @@ -578,7 +580,7 @@ public function testValidateUniquenessWithArrayValue() public function testDedicatedEntityManagerNullObject() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('Object manager "foo" does not exist.'); $constraint = new UniqueEntity([ 'message' => 'myMessage', @@ -598,7 +600,7 @@ public function testDedicatedEntityManagerNullObject() public function testEntityManagerNullObject() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('Unable to find the object manager associated with an entity of class "Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity"'); $constraint = new UniqueEntity([ 'message' => 'myMessage', @@ -650,7 +652,7 @@ public function testValidateInheritanceUniqueness() 'message' => 'myMessage', 'fields' => ['name'], 'em' => self::EM_NAME, - 'entityClass' => 'Symfony\Bridge\Doctrine\Tests\Fixtures\Person', + 'entityClass' => Person::class, ]); $entity1 = new Person(1, 'Foo'); @@ -680,13 +682,13 @@ public function testValidateInheritanceUniqueness() public function testInvalidateRepositoryForInheritance() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('The "Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity" entity repository does not support the "Symfony\Bridge\Doctrine\Tests\Fixtures\Person" entity. The entity should be an instance of or extend "Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity".'); $constraint = new UniqueEntity([ 'message' => 'myMessage', 'fields' => ['name'], 'em' => self::EM_NAME, - 'entityClass' => 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity', + 'entityClass' => SingleStringIdEntity::class, ]); $entity = new Person(1, 'Foo'); diff --git a/src/Symfony/Bridge/Monolog/Tests/Handler/ConsoleHandlerTest.php b/src/Symfony/Bridge/Monolog/Tests/Handler/ConsoleHandlerTest.php index 49151e142859..d61692ed7646 100644 --- a/src/Symfony/Bridge/Monolog/Tests/Handler/ConsoleHandlerTest.php +++ b/src/Symfony/Bridge/Monolog/Tests/Handler/ConsoleHandlerTest.php @@ -13,12 +13,15 @@ use Monolog\Logger; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\Monolog\Formatter\ConsoleFormatter; use Symfony\Bridge\Monolog\Handler\ConsoleHandler; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\ConsoleEvents; use Symfony\Component\Console\Event\ConsoleCommandEvent; use Symfony\Component\Console\Event\ConsoleTerminateEvent; +use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\BufferedOutput; +use Symfony\Component\Console\Output\Output; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\EventDispatcher\EventDispatcher; @@ -46,7 +49,7 @@ public function testIsHandling() */ public function testVerbosityMapping($verbosity, $level, $isHandling, array $map = []) { - $output = $this->getMockBuilder(OutputInterface::class)->getMock(); + $output = $this->createMock(OutputInterface::class); $output ->expects($this->atLeastOnce()) ->method('getVerbosity') @@ -61,7 +64,7 @@ public function testVerbosityMapping($verbosity, $level, $isHandling, array $map $levelName = Logger::getLevelName($level); $levelName = sprintf('%-9s', $levelName); - $realOutput = $this->getMockBuilder(\Symfony\Component\Console\Output\Output::class)->setMethods(['doWrite'])->getMock(); + $realOutput = $this->getMockBuilder(Output::class)->setMethods(['doWrite'])->getMock(); $realOutput->setVerbosity($verbosity); if ($realOutput->isDebug()) { $log = "16:21:54 $levelName [app] My info message\n"; @@ -110,7 +113,7 @@ public function provideVerbosityMappingTests() public function testVerbosityChanged() { - $output = $this->getMockBuilder(OutputInterface::class)->getMock(); + $output = $this->createMock(OutputInterface::class); $output ->expects($this->exactly(2)) ->method('getVerbosity') @@ -131,14 +134,15 @@ public function testVerbosityChanged() public function testGetFormatter() { $handler = new ConsoleHandler(); - $this->assertInstanceOf(\Symfony\Bridge\Monolog\Formatter\ConsoleFormatter::class, $handler->getFormatter(), - '-getFormatter returns ConsoleFormatter by default' + $this->assertInstanceOf( + ConsoleFormatter::class, $handler->getFormatter(), + '->getFormatter returns ConsoleFormatter by default' ); } public function testWritingAndFormatting() { - $output = $this->getMockBuilder(OutputInterface::class)->getMock(); + $output = $this->createMock(OutputInterface::class); $output ->expects($this->any()) ->method('getVerbosity') @@ -193,12 +197,12 @@ public function testLogsFromListeners() $logger->info('After terminate message.'); }); - $event = new ConsoleCommandEvent(new Command('foo'), $this->getMockBuilder(\Symfony\Component\Console\Input\InputInterface::class)->getMock(), $output); + $event = new ConsoleCommandEvent(new Command('foo'), $this->createMock(InputInterface::class), $output); $dispatcher->dispatch($event, ConsoleEvents::COMMAND); $this->assertStringContainsString('Before command message.', $out = $output->fetch()); $this->assertStringContainsString('After command message.', $out); - $event = new ConsoleTerminateEvent(new Command('foo'), $this->getMockBuilder(\Symfony\Component\Console\Input\InputInterface::class)->getMock(), $output, 0); + $event = new ConsoleTerminateEvent(new Command('foo'), $this->createMock(InputInterface::class), $output, 0); $dispatcher->dispatch($event, ConsoleEvents::TERMINATE); $this->assertStringContainsString('Before terminate message.', $out = $output->fetch()); $this->assertStringContainsString('After terminate message.', $out); diff --git a/src/Symfony/Bridge/Monolog/Tests/Handler/ServerLogHandlerTest.php b/src/Symfony/Bridge/Monolog/Tests/Handler/ServerLogHandlerTest.php index 0664727995a6..f5a4405f645f 100644 --- a/src/Symfony/Bridge/Monolog/Tests/Handler/ServerLogHandlerTest.php +++ b/src/Symfony/Bridge/Monolog/Tests/Handler/ServerLogHandlerTest.php @@ -44,7 +44,7 @@ public function testGetFormatter() { $handler = new ServerLogHandler('tcp://127.0.0.1:9999'); $this->assertInstanceOf(VarDumperFormatter::class, $handler->getFormatter(), - '-getFormatter returns VarDumperFormatter by default' + '->getFormatter returns VarDumperFormatter by default' ); } diff --git a/src/Symfony/Bridge/Monolog/Tests/LoggerTest.php b/src/Symfony/Bridge/Monolog/Tests/LoggerTest.php index c6f34799fc7d..12b687e115cd 100644 --- a/src/Symfony/Bridge/Monolog/Tests/LoggerTest.php +++ b/src/Symfony/Bridge/Monolog/Tests/LoggerTest.php @@ -84,7 +84,7 @@ public function testGetLogsWithDebugProcessor2() public function testGetLogsWithDebugProcessor3() { $request = new Request(); - $processor = $this->getMockBuilder(DebugProcessor::class)->getMock(); + $processor = $this->createMock(DebugProcessor::class); $processor->expects($this->once())->method('getLogs')->with($request); $processor->expects($this->once())->method('countErrors')->with($request); diff --git a/src/Symfony/Bridge/Monolog/Tests/Processor/ConsoleCommandProcessorTest.php b/src/Symfony/Bridge/Monolog/Tests/Processor/ConsoleCommandProcessorTest.php index 4c9774b4a438..6ee30da38a99 100644 --- a/src/Symfony/Bridge/Monolog/Tests/Processor/ConsoleCommandProcessorTest.php +++ b/src/Symfony/Bridge/Monolog/Tests/Processor/ConsoleCommandProcessorTest.php @@ -61,12 +61,12 @@ public function testProcessorDoesNothingWhenNotInConsole() private function getConsoleEvent(): ConsoleEvent { - $input = $this->getMockBuilder(InputInterface::class)->getMock(); + $input = $this->createMock(InputInterface::class); $input->method('getArguments')->willReturn(self::TEST_ARGUMENTS); $input->method('getOptions')->willReturn(self::TEST_OPTIONS); - $command = $this->getMockBuilder(Command::class)->disableOriginalConstructor()->getMock(); + $command = $this->createMock(Command::class); $command->method('getName')->willReturn(self::TEST_NAME); - $consoleEvent = $this->getMockBuilder(ConsoleEvent::class)->disableOriginalConstructor()->getMock(); + $consoleEvent = $this->createMock(ConsoleEvent::class); $consoleEvent->method('getCommand')->willReturn($command); $consoleEvent->method('getInput')->willReturn($input); diff --git a/src/Symfony/Bridge/Monolog/Tests/Processor/RouteProcessorTest.php b/src/Symfony/Bridge/Monolog/Tests/Processor/RouteProcessorTest.php index 3ac4ed04508a..06336f1a593c 100644 --- a/src/Symfony/Bridge/Monolog/Tests/Processor/RouteProcessorTest.php +++ b/src/Symfony/Bridge/Monolog/Tests/Processor/RouteProcessorTest.php @@ -149,7 +149,7 @@ private function mockFilledRequest(string $controller = self::TEST_CONTROLLER): private function mockRequest(array $attributes): Request { - $request = $this->getMockBuilder(Request::class)->disableOriginalConstructor()->getMock(); + $request = $this->createMock(Request::class); $request->attributes = new ParameterBag($attributes); return $request; diff --git a/src/Symfony/Bridge/Monolog/Tests/Processor/TokenProcessorTest.php b/src/Symfony/Bridge/Monolog/Tests/Processor/TokenProcessorTest.php index ef3f6cc9f5c6..dcaf0f647e30 100644 --- a/src/Symfony/Bridge/Monolog/Tests/Processor/TokenProcessorTest.php +++ b/src/Symfony/Bridge/Monolog/Tests/Processor/TokenProcessorTest.php @@ -26,7 +26,7 @@ class TokenProcessorTest extends TestCase public function testProcessor() { $token = new UsernamePasswordToken('user', 'password', 'provider', ['ROLE_USER']); - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage->method('getToken')->willReturn($token); $processor = new TokenProcessor($tokenStorage); diff --git a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Dumper/PhpDumperTest.php b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Dumper/PhpDumperTest.php index 6a2935f5f154..8bc017bb8df7 100644 --- a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Dumper/PhpDumperTest.php +++ b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Dumper/PhpDumperTest.php @@ -12,6 +12,7 @@ namespace Symfony\Bridge\ProxyManager\Tests\LazyProxy\Dumper; use PHPUnit\Framework\TestCase; +use ProxyManager\Proxy\LazyLoadingInterface; use Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Dumper\PhpDumper; @@ -46,7 +47,7 @@ public function testDumpContainerWithProxyServiceWillShareProxies() $proxy = $container->get('foo'); $this->assertInstanceOf(\stdClass::class, $proxy); - $this->assertInstanceOf(\ProxyManager\Proxy\LazyLoadingInterface::class, $proxy); + $this->assertInstanceOf(LazyLoadingInterface::class, $proxy); $this->assertSame($proxy, $container->get('foo')); $this->assertFalse($proxy->isProxyInitialized()); diff --git a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Instantiator/RuntimeInstantiatorTest.php b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Instantiator/RuntimeInstantiatorTest.php index 467397296102..e202fad70265 100644 --- a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Instantiator/RuntimeInstantiatorTest.php +++ b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Instantiator/RuntimeInstantiatorTest.php @@ -12,7 +12,10 @@ namespace Symfony\Bridge\ProxyManager\Tests\LazyProxy\Instantiator; use PHPUnit\Framework\TestCase; +use ProxyManager\Proxy\LazyLoadingInterface; +use ProxyManager\Proxy\ValueHolderInterface; use Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Definition; /** @@ -38,17 +41,17 @@ protected function setUp(): void public function testInstantiateProxy() { $instance = new \stdClass(); - $container = $this->getMockBuilder(\Symfony\Component\DependencyInjection\ContainerInterface::class)->getMock(); + $container = $this->createMock(ContainerInterface::class); $definition = new Definition('stdClass'); $instantiator = function () use ($instance) { return $instance; }; - /* @var $proxy \ProxyManager\Proxy\LazyLoadingInterface|\ProxyManager\Proxy\ValueHolderInterface */ + /* @var $proxy LazyLoadingInterface|ValueHolderInterface */ $proxy = $this->instantiator->instantiateProxy($container, $definition, 'foo', $instantiator); - $this->assertInstanceOf(\ProxyManager\Proxy\LazyLoadingInterface::class, $proxy); - $this->assertInstanceOf(\ProxyManager\Proxy\ValueHolderInterface::class, $proxy); + $this->assertInstanceOf(LazyLoadingInterface::class, $proxy); + $this->assertInstanceOf(ValueHolderInterface::class, $proxy); $this->assertFalse($proxy->isProxyInitialized()); $proxy->initializeProxy(); diff --git a/src/Symfony/Bridge/Twig/Tests/AppVariableTest.php b/src/Symfony/Bridge/Twig/Tests/AppVariableTest.php index 044827110d1d..f5fcbeada656 100644 --- a/src/Symfony/Bridge/Twig/Tests/AppVariableTest.php +++ b/src/Symfony/Bridge/Twig/Tests/AppVariableTest.php @@ -5,8 +5,12 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\AppVariable; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; use Symfony\Component\HttpFoundation\Session\Session; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; +use Symfony\Component\Security\Core\User\UserInterface; class AppVariableTest extends TestCase { @@ -50,7 +54,7 @@ public function testEnvironment() */ public function testGetSession() { - $request = $this->getMockBuilder(Request::class)->getMock(); + $request = $this->createMock(Request::class); $request->method('hasSession')->willReturn(true); $request->method('getSession')->willReturn($session = new Session()); @@ -75,10 +79,10 @@ public function testGetRequest() public function testGetToken() { - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $this->appVariable->setTokenStorage($tokenStorage); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $tokenStorage->method('getToken')->willReturn($token); $this->assertEquals($token, $this->appVariable->getToken()); @@ -86,7 +90,7 @@ public function testGetToken() public function testGetUser() { - $this->setTokenStorage($user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock()); + $this->setTokenStorage($user = $this->createMock(UserInterface::class)); $this->assertEquals($user, $this->appVariable->getUser()); } @@ -100,7 +104,7 @@ public function testGetUserWithUsernameAsTokenUser() public function testGetTokenWithNoToken() { - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $this->appVariable->setTokenStorage($tokenStorage); $this->assertNull($this->appVariable->getToken()); @@ -108,7 +112,7 @@ public function testGetTokenWithNoToken() public function testGetUserWithNoToken() { - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $this->appVariable->setTokenStorage($tokenStorage); $this->assertNull($this->appVariable->getUser()); @@ -224,7 +228,7 @@ public function testGetFlashes() protected function setRequestStack($request) { - $requestStackMock = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestStack::class)->getMock(); + $requestStackMock = $this->createMock(RequestStack::class); $requestStackMock->method('getCurrentRequest')->willReturn($request); $this->appVariable->setRequestStack($requestStackMock); @@ -232,10 +236,10 @@ protected function setRequestStack($request) protected function setTokenStorage($user) { - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $this->appVariable->setTokenStorage($tokenStorage); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $tokenStorage->method('getToken')->willReturn($token); $token->method('getUser')->willReturn($user); @@ -251,11 +255,11 @@ private function setFlashMessages($sessionHasStarted = true) $flashBag = new FlashBag(); $flashBag->initialize($flashMessages); - $session = $this->getMockBuilder(Session::class)->disableOriginalConstructor()->getMock(); + $session = $this->createMock(Session::class); $session->method('isStarted')->willReturn($sessionHasStarted); $session->method('getFlashBag')->willReturn($flashBag); - $request = $this->getMockBuilder(Request::class)->getMock(); + $request = $this->createMock(Request::class); $request->method('hasSession')->willReturn(true); $request->method('getSession')->willReturn($session); $this->setRequestStack($request); diff --git a/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php b/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php index 8be4a64bd65a..9fa1af4759ea 100644 --- a/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\Command\DebugCommand; use Symfony\Component\Console\Application; +use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Tester\CommandTester; use Twig\Environment; use Twig\Loader\ChainLoader; @@ -91,7 +92,7 @@ public function testDeprecationForWrongBundleOverridingInLegacyPath() public function testMalformedTemplateName() { - $this->expectException(\Symfony\Component\Console\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Malformed namespaced template name "@foo" (expecting "@namespace/template_name").'); $this->createCommandTester()->execute(['name' => '@foo']); } diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/DumpExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/DumpExtensionTest.php index bd6e58b5edef..d0825221663a 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/DumpExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/DumpExtensionTest.php @@ -18,6 +18,7 @@ use Symfony\Component\VarDumper\VarDumper; use Twig\Environment; use Twig\Loader\ArrayLoader; +use Twig\Loader\LoaderInterface; class DumpExtensionTest extends TestCase { @@ -67,7 +68,7 @@ public function getDumpTags() public function testDump($context, $args, $expectedOutput, $debug = true) { $extension = new DumpExtension(new VarCloner()); - $twig = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock(), [ + $twig = new Environment($this->createMock(LoaderInterface::class), [ 'debug' => $debug, 'cache' => false, 'optimizations' => 0, @@ -124,7 +125,7 @@ public function testCustomDumper() '' ); $extension = new DumpExtension(new VarCloner(), $dumper); - $twig = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock(), [ + $twig = new Environment($this->createMock(LoaderInterface::class), [ 'debug' => true, 'cache' => false, 'optimizations' => 0, diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php index 425b489fec0e..d8e8468c3f4b 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php @@ -18,6 +18,7 @@ use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubTranslator; use Symfony\Component\Form\FormRenderer; use Symfony\Component\Form\FormView; +use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Twig\Environment; class FormExtensionBootstrap3HorizontalLayoutTest extends AbstractBootstrap3HorizontalLayoutTest @@ -50,7 +51,7 @@ protected function setUp(): void 'bootstrap_3_horizontal_layout.html.twig', 'custom_widgets.html.twig', ], $environment); - $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder(\Symfony\Component\Security\Csrf\CsrfTokenManagerInterface::class)->getMock()); + $this->renderer = new FormRenderer($rendererEngine, $this->createMock(CsrfTokenManagerInterface::class)); $this->registerTwigRuntimeLoader($environment, $this->renderer); } diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3LayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3LayoutTest.php index b20768b9116f..0735cc2973e6 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3LayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3LayoutTest.php @@ -18,6 +18,7 @@ use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubTranslator; use Symfony\Component\Form\FormRenderer; use Symfony\Component\Form\FormView; +use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Twig\Environment; class FormExtensionBootstrap3LayoutTest extends AbstractBootstrap3LayoutTest @@ -46,7 +47,7 @@ protected function setUp(): void 'bootstrap_3_layout.html.twig', 'custom_widgets.html.twig', ], $environment); - $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder(\Symfony\Component\Security\Csrf\CsrfTokenManagerInterface::class)->getMock()); + $this->renderer = new FormRenderer($rendererEngine, $this->createMock(CsrfTokenManagerInterface::class)); $this->registerTwigRuntimeLoader($environment, $this->renderer); } @@ -88,7 +89,7 @@ public function testMoneyWidgetInIso() 'bootstrap_3_layout.html.twig', 'custom_widgets.html.twig', ], $environment); - $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder(\Symfony\Component\Security\Csrf\CsrfTokenManagerInterface::class)->getMock()); + $this->renderer = new FormRenderer($rendererEngine, $this->createMock(CsrfTokenManagerInterface::class)); $this->registerTwigRuntimeLoader($environment, $this->renderer); $view = $this->factory diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4HorizontalLayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4HorizontalLayoutTest.php index 70713ef59a1f..da0564851229 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4HorizontalLayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4HorizontalLayoutTest.php @@ -18,6 +18,7 @@ use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubTranslator; use Symfony\Component\Form\FormRenderer; use Symfony\Component\Form\FormView; +use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Twig\Environment; /** @@ -52,7 +53,7 @@ protected function setUp(): void 'bootstrap_4_horizontal_layout.html.twig', 'custom_widgets.html.twig', ], $environment); - $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder(\Symfony\Component\Security\Csrf\CsrfTokenManagerInterface::class)->getMock()); + $this->renderer = new FormRenderer($rendererEngine, $this->createMock(CsrfTokenManagerInterface::class)); $this->registerTwigRuntimeLoader($environment, $this->renderer); } diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4LayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4LayoutTest.php index c489bfb425e8..f62e903473ca 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4LayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4LayoutTest.php @@ -18,6 +18,7 @@ use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubTranslator; use Symfony\Component\Form\FormRenderer; use Symfony\Component\Form\FormView; +use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Twig\Environment; /** @@ -50,7 +51,7 @@ protected function setUp(): void 'bootstrap_4_layout.html.twig', 'custom_widgets.html.twig', ], $environment); - $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder(\Symfony\Component\Security\Csrf\CsrfTokenManagerInterface::class)->getMock()); + $this->renderer = new FormRenderer($rendererEngine, $this->createMock(CsrfTokenManagerInterface::class)); $this->registerTwigRuntimeLoader($environment, $this->renderer); } @@ -92,7 +93,7 @@ public function testMoneyWidgetInIso() 'bootstrap_4_layout.html.twig', 'custom_widgets.html.twig', ], $environment); - $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder(\Symfony\Component\Security\Csrf\CsrfTokenManagerInterface::class)->getMock()); + $this->renderer = new FormRenderer($rendererEngine, $this->createMock(CsrfTokenManagerInterface::class)); $this->registerTwigRuntimeLoader($environment, $this->renderer); $view = $this->factory diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php index 61e91ebd0a0d..9e7b1684b826 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php @@ -20,6 +20,7 @@ use Symfony\Component\Form\FormRenderer; use Symfony\Component\Form\FormView; use Symfony\Component\Form\Tests\AbstractDivLayoutTest; +use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Twig\Environment; class FormExtensionDivLayoutTest extends AbstractDivLayoutTest @@ -53,7 +54,7 @@ protected function setUp(): void 'form_div_layout.html.twig', 'custom_widgets.html.twig', ], $environment); - $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder(\Symfony\Component\Security\Csrf\CsrfTokenManagerInterface::class)->getMock()); + $this->renderer = new FormRenderer($rendererEngine, $this->createMock(CsrfTokenManagerInterface::class)); $this->registerTwigRuntimeLoader($environment, $this->renderer); } @@ -181,7 +182,7 @@ public function testMoneyWidgetInIso() 'form_div_layout.html.twig', 'custom_widgets.html.twig', ], $environment); - $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder(\Symfony\Component\Security\Csrf\CsrfTokenManagerInterface::class)->getMock()); + $this->renderer = new FormRenderer($rendererEngine, $this->createMock(CsrfTokenManagerInterface::class)); $this->registerTwigRuntimeLoader($environment, $this->renderer); $view = $this->factory diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php index 629677832f94..ecf3597b311a 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php @@ -19,6 +19,7 @@ use Symfony\Component\Form\FormRenderer; use Symfony\Component\Form\FormView; use Symfony\Component\Form\Tests\AbstractTableLayoutTest; +use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Twig\Environment; class FormExtensionTableLayoutTest extends AbstractTableLayoutTest @@ -50,7 +51,7 @@ protected function setUp(): void 'form_table_layout.html.twig', 'custom_widgets.html.twig', ], $environment); - $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder(\Symfony\Component\Security\Csrf\CsrfTokenManagerInterface::class)->getMock()); + $this->renderer = new FormRenderer($rendererEngine, $this->createMock(CsrfTokenManagerInterface::class)); $this->registerTwigRuntimeLoader($environment, $this->renderer); } diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php index 83ca06fbabf3..5fa1ef3bad62 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php @@ -15,10 +15,13 @@ use Symfony\Bridge\Twig\Extension\HttpKernelExtension; use Symfony\Bridge\Twig\Extension\HttpKernelRuntime; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Fragment\FragmentHandler; +use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface; use Twig\Environment; use Twig\Loader\ArrayLoader; +use Twig\RuntimeLoader\RuntimeLoaderInterface; class HttpKernelExtensionTest extends TestCase { @@ -41,10 +44,7 @@ public function testRenderFragment() public function testUnknownFragmentRenderer() { - $context = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestStack::class) - ->disableOriginalConstructor() - ->getMock() - ; + $context = $this->createMock(RequestStack::class); $renderer = new FragmentHandler($context); $this->expectException(\InvalidArgumentException::class); @@ -55,14 +55,11 @@ public function testUnknownFragmentRenderer() protected function getFragmentHandler($return) { - $strategy = $this->getMockBuilder(\Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface::class)->getMock(); + $strategy = $this->createMock(FragmentRendererInterface::class); $strategy->expects($this->once())->method('getName')->willReturn('inline'); $strategy->expects($this->once())->method('render')->will($return); - $context = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestStack::class) - ->disableOriginalConstructor() - ->getMock() - ; + $context = $this->createMock(RequestStack::class); $context->expects($this->any())->method('getCurrentRequest')->willReturn(Request::create('/')); @@ -75,7 +72,7 @@ protected function renderTemplate(FragmentHandler $renderer, $template = '{{ ren $twig = new Environment($loader, ['debug' => true, 'cache' => false]); $twig->addExtension(new HttpKernelExtension()); - $loader = $this->getMockBuilder(\Twig\RuntimeLoader\RuntimeLoaderInterface::class)->getMock(); + $loader = $this->createMock(RuntimeLoaderInterface::class); $loader->expects($this->any())->method('load')->willReturnMap([ ['Symfony\Bridge\Twig\Extension\HttpKernelRuntime', new HttpKernelRuntime($renderer)], ]); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/RoutingExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/RoutingExtensionTest.php index 7362702bd233..5a995c8eeb76 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/RoutingExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/RoutingExtensionTest.php @@ -13,7 +13,9 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\Extension\RoutingExtension; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Twig\Environment; +use Twig\Loader\LoaderInterface; use Twig\Node\Expression\FilterExpression; use Twig\Source; @@ -24,8 +26,8 @@ class RoutingExtensionTest extends TestCase */ public function testEscaping($template, $mustBeEscaped) { - $twig = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock(), ['debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0]); - $twig->addExtension(new RoutingExtension($this->getMockBuilder(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class)->getMock())); + $twig = new Environment($this->createMock(LoaderInterface::class), ['debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0]); + $twig->addExtension(new RoutingExtension($this->createMock(UrlGeneratorInterface::class))); $nodes = $twig->parse($twig->tokenize(new Source($template, ''))); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/RuntimeLoaderProvider.php b/src/Symfony/Bridge/Twig/Tests/Extension/RuntimeLoaderProvider.php index f3ef88583494..dea148192475 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/RuntimeLoaderProvider.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/RuntimeLoaderProvider.php @@ -13,12 +13,13 @@ use Symfony\Component\Form\FormRenderer; use Twig\Environment; +use Twig\RuntimeLoader\RuntimeLoaderInterface; trait RuntimeLoaderProvider { protected function registerTwigRuntimeLoader(Environment $environment, FormRenderer $renderer) { - $loader = $this->getMockBuilder(\Twig\RuntimeLoader\RuntimeLoaderInterface::class)->getMock(); + $loader = $this->createMock(RuntimeLoaderInterface::class); $loader->expects($this->any())->method('load')->will($this->returnValueMap([ ['Symfony\Component\Form\FormRenderer', $renderer], ])); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.php index 8f7ef97e9cf7..65f1bd69bff7 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\Extension\StopwatchExtension; +use Symfony\Component\Stopwatch\Stopwatch; use Twig\Environment; use Twig\Error\RuntimeError; use Twig\Loader\ArrayLoader; @@ -55,7 +56,7 @@ public function getTimingTemplates() protected function getStopwatch($events = []) { $events = \is_array($events) ? $events : [$events]; - $stopwatch = $this->getMockBuilder(\Symfony\Component\Stopwatch\Stopwatch::class)->getMock(); + $stopwatch = $this->createMock(Stopwatch::class); $expectedCalls = 0; $expectedStartCalls = []; diff --git a/src/Symfony/Bridge/Twig/Tests/Node/DumpNodeTest.php b/src/Symfony/Bridge/Twig/Tests/Node/DumpNodeTest.php index 89afd4ab2d87..f655a04ae3bd 100644 --- a/src/Symfony/Bridge/Twig/Tests/Node/DumpNodeTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Node/DumpNodeTest.php @@ -15,6 +15,7 @@ use Symfony\Bridge\Twig\Node\DumpNode; use Twig\Compiler; use Twig\Environment; +use Twig\Loader\LoaderInterface; use Twig\Node\Expression\NameExpression; use Twig\Node\Node; @@ -24,7 +25,7 @@ public function testNoVar() { $node = new DumpNode('bar', null, 7); - $env = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock()); + $env = new Environment($this->createMock(LoaderInterface::class)); $compiler = new Compiler($env); $expected = <<<'EOTXT' @@ -48,7 +49,7 @@ public function testIndented() { $node = new DumpNode('bar', null, 7); - $env = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock()); + $env = new Environment($this->createMock(LoaderInterface::class)); $compiler = new Compiler($env); $expected = <<<'EOTXT' @@ -75,7 +76,7 @@ public function testOneVar() ]); $node = new DumpNode('bar', $vars, 7); - $env = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock()); + $env = new Environment($this->createMock(LoaderInterface::class)); $compiler = new Compiler($env); $expected = <<<'EOTXT' @@ -99,7 +100,7 @@ public function testMultiVars() ]); $node = new DumpNode('bar', $vars, 7); - $env = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock()); + $env = new Environment($this->createMock(LoaderInterface::class)); $compiler = new Compiler($env); $expected = <<<'EOTXT' diff --git a/src/Symfony/Bridge/Twig/Tests/Node/FormThemeTest.php b/src/Symfony/Bridge/Twig/Tests/Node/FormThemeTest.php index 99a1e7fde222..89d4460fa98c 100644 --- a/src/Symfony/Bridge/Twig/Tests/Node/FormThemeTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Node/FormThemeTest.php @@ -18,6 +18,7 @@ use Symfony\Component\Form\FormRendererEngineInterface; use Twig\Compiler; use Twig\Environment; +use Twig\Loader\LoaderInterface; use Twig\Node\Expression\ArrayExpression; use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\NameExpression; @@ -54,8 +55,8 @@ public function testCompile() $node = new FormThemeNode($form, $resources, 0); - $environment = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock()); - $formRenderer = new FormRenderer($this->getMockBuilder(FormRendererEngineInterface::class)->getMock()); + $environment = new Environment($this->createMock(LoaderInterface::class)); + $formRenderer = new FormRenderer($this->createMock(FormRendererEngineInterface::class)); $this->registerTwigRuntimeLoader($environment, $formRenderer); $compiler = new Compiler($environment); diff --git a/src/Symfony/Bridge/Twig/Tests/Node/SearchAndRenderBlockNodeTest.php b/src/Symfony/Bridge/Twig/Tests/Node/SearchAndRenderBlockNodeTest.php index b7cb67818987..59a8b10a9d06 100644 --- a/src/Symfony/Bridge/Twig/Tests/Node/SearchAndRenderBlockNodeTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Node/SearchAndRenderBlockNodeTest.php @@ -15,6 +15,7 @@ use Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode; use Twig\Compiler; use Twig\Environment; +use Twig\Loader\LoaderInterface; use Twig\Node\Expression\ArrayExpression; use Twig\Node\Expression\ConditionalExpression; use Twig\Node\Expression\ConstantExpression; @@ -31,7 +32,7 @@ public function testCompileWidget() $node = new SearchAndRenderBlockNode('form_widget', $arguments, 0); - $compiler = new Compiler(new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock())); + $compiler = new Compiler(new Environment($this->createMock(LoaderInterface::class))); $this->assertEquals( sprintf( @@ -54,7 +55,7 @@ public function testCompileWidgetWithVariables() $node = new SearchAndRenderBlockNode('form_widget', $arguments, 0); - $compiler = new Compiler(new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock())); + $compiler = new Compiler(new Environment($this->createMock(LoaderInterface::class))); $this->assertEquals( sprintf( @@ -74,7 +75,7 @@ public function testCompileLabelWithLabel() $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new Compiler(new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock())); + $compiler = new Compiler(new Environment($this->createMock(LoaderInterface::class))); $this->assertEquals( sprintf( @@ -94,7 +95,7 @@ public function testCompileLabelWithNullLabel() $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new Compiler(new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock())); + $compiler = new Compiler(new Environment($this->createMock(LoaderInterface::class))); // "label" => null must not be included in the output! // Otherwise the default label is overwritten with null. @@ -116,7 +117,7 @@ public function testCompileLabelWithEmptyStringLabel() $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new Compiler(new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock())); + $compiler = new Compiler(new Environment($this->createMock(LoaderInterface::class))); // "label" => null must not be included in the output! // Otherwise the default label is overwritten with null. @@ -137,7 +138,7 @@ public function testCompileLabelWithDefaultLabel() $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new Compiler(new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock())); + $compiler = new Compiler(new Environment($this->createMock(LoaderInterface::class))); $this->assertEquals( sprintf( @@ -161,7 +162,7 @@ public function testCompileLabelWithAttributes() $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new Compiler(new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock())); + $compiler = new Compiler(new Environment($this->createMock(LoaderInterface::class))); // "label" => null must not be included in the output! // Otherwise the default label is overwritten with null. @@ -190,7 +191,7 @@ public function testCompileLabelWithLabelAndAttributes() $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new Compiler(new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock())); + $compiler = new Compiler(new Environment($this->createMock(LoaderInterface::class))); $this->assertEquals( sprintf( @@ -218,7 +219,7 @@ public function testCompileLabelWithLabelThatEvaluatesToNull() $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new Compiler(new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock())); + $compiler = new Compiler(new Environment($this->createMock(LoaderInterface::class))); // "label" => null must not be included in the output! // Otherwise the default label is overwritten with null. @@ -255,7 +256,7 @@ public function testCompileLabelWithLabelThatEvaluatesToNullAndAttributes() $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new Compiler(new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock())); + $compiler = new Compiler(new Environment($this->createMock(LoaderInterface::class))); // "label" => null must not be included in the output! // Otherwise the default label is overwritten with null. diff --git a/src/Symfony/Bridge/Twig/Tests/Node/TransNodeTest.php b/src/Symfony/Bridge/Twig/Tests/Node/TransNodeTest.php index 2acf695e5618..72997273aced 100644 --- a/src/Symfony/Bridge/Twig/Tests/Node/TransNodeTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Node/TransNodeTest.php @@ -15,6 +15,7 @@ use Symfony\Bridge\Twig\Node\TransNode; use Twig\Compiler; use Twig\Environment; +use Twig\Loader\LoaderInterface; use Twig\Node\Expression\NameExpression; use Twig\Node\TextNode; @@ -29,7 +30,7 @@ public function testCompileStrict() $vars = new NameExpression('foo', 0); $node = new TransNode($body, null, null, $vars); - $env = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock(), ['strict_variables' => true]); + $env = new Environment($this->createMock(LoaderInterface::class), ['strict_variables' => true]); $compiler = new Compiler($env); $this->assertEquals( diff --git a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.php b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.php index 3f1de5bb1ea2..1c3d42d1a319 100644 --- a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.php +++ b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.php @@ -15,6 +15,7 @@ use Symfony\Bridge\Twig\NodeVisitor\TranslationDefaultDomainNodeVisitor; use Symfony\Bridge\Twig\NodeVisitor\TranslationNodeVisitor; use Twig\Environment; +use Twig\Loader\LoaderInterface; use Twig\Node\Expression\ArrayExpression; use Twig\Node\Node; @@ -26,7 +27,7 @@ class TranslationDefaultDomainNodeVisitorTest extends TestCase /** @dataProvider getDefaultDomainAssignmentTestData */ public function testDefaultDomainAssignment(Node $node) { - $env = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock(), ['cache' => false, 'autoescape' => false, 'optimizations' => 0]); + $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false, 'optimizations' => 0]); $visitor = new TranslationDefaultDomainNodeVisitor(); // visit trans_default_domain tag @@ -52,7 +53,7 @@ public function testDefaultDomainAssignment(Node $node) /** @dataProvider getDefaultDomainAssignmentTestData */ public function testNewModuleWithoutDefaultDomainTag(Node $node) { - $env = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock(), ['cache' => false, 'autoescape' => false, 'optimizations' => 0]); + $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false, 'optimizations' => 0]); $visitor = new TranslationDefaultDomainNodeVisitor(); // visit trans_default_domain tag diff --git a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.php b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.php index 57da0628f6c1..8d8b77c3acf5 100644 --- a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.php +++ b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\NodeVisitor\TranslationNodeVisitor; use Twig\Environment; +use Twig\Loader\LoaderInterface; use Twig\Node\Expression\ArrayExpression; use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\FilterExpression; @@ -25,7 +26,7 @@ class TranslationNodeVisitorTest extends TestCase /** @dataProvider getMessagesExtractionTestData */ public function testMessagesExtraction(Node $node, array $expectedMessages) { - $env = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock(), ['cache' => false, 'autoescape' => false, 'optimizations' => 0]); + $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false, 'optimizations' => 0]); $visitor = new TranslationNodeVisitor(); $visitor->enable(); $visitor->enterNode($node, $env); diff --git a/src/Symfony/Bridge/Twig/Tests/TokenParser/FormThemeTokenParserTest.php b/src/Symfony/Bridge/Twig/Tests/TokenParser/FormThemeTokenParserTest.php index 69fb98a631c6..d404060091f8 100644 --- a/src/Symfony/Bridge/Twig/Tests/TokenParser/FormThemeTokenParserTest.php +++ b/src/Symfony/Bridge/Twig/Tests/TokenParser/FormThemeTokenParserTest.php @@ -15,6 +15,7 @@ use Symfony\Bridge\Twig\Node\FormThemeNode; use Symfony\Bridge\Twig\TokenParser\FormThemeTokenParser; use Twig\Environment; +use Twig\Loader\LoaderInterface; use Twig\Node\Expression\ArrayExpression; use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\NameExpression; @@ -28,7 +29,7 @@ class FormThemeTokenParserTest extends TestCase */ public function testCompile($source, $expected) { - $env = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock(), ['cache' => false, 'autoescape' => false, 'optimizations' => 0]); + $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false, 'optimizations' => 0]); $env->addTokenParser(new FormThemeTokenParser()); $source = new Source($source, ''); $stream = $env->tokenize($source); diff --git a/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php b/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php index 21e78322d3b7..5dfc6ea450e0 100644 --- a/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php @@ -18,6 +18,7 @@ use Symfony\Contracts\Translation\TranslatorInterface; use Twig\Environment; use Twig\Loader\ArrayLoader; +use Twig\Loader\LoaderInterface; class TwigExtractorTest extends TestCase { @@ -26,14 +27,14 @@ class TwigExtractorTest extends TestCase */ public function testExtract($template, $messages) { - $loader = $this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $twig = new Environment($loader, [ 'strict_variables' => true, 'debug' => true, 'cache' => false, 'autoescape' => false, ]); - $twig->addExtension(new TranslationExtension($this->getMockBuilder(TranslatorInterface::class)->getMock())); + $twig->addExtension(new TranslationExtension($this->createMock(TranslatorInterface::class))); $extractor = new TwigExtractor($twig); $extractor->setPrefix('prefix'); @@ -102,8 +103,8 @@ public function getLegacyExtractData() */ public function testExtractSyntaxError($resources, array $messages) { - $twig = new Environment($this->getMockBuilder(\Twig\Loader\LoaderInterface::class)->getMock()); - $twig->addExtension(new TranslationExtension($this->getMockBuilder(TranslatorInterface::class)->getMock())); + $twig = new Environment($this->createMock(LoaderInterface::class)); + $twig->addExtension(new TranslationExtension($this->createMock(TranslatorInterface::class))); $extractor = new TwigExtractor($twig); $catalogue = new MessageCatalogue('en'); @@ -132,7 +133,7 @@ public function testExtractWithFiles($resource) 'cache' => false, 'autoescape' => false, ]); - $twig->addExtension(new TranslationExtension($this->getMockBuilder(TranslatorInterface::class)->getMock())); + $twig->addExtension(new TranslationExtension($this->createMock(TranslatorInterface::class))); $extractor = new TwigExtractor($twig); $catalogue = new MessageCatalogue('en'); diff --git a/src/Symfony/Bridge/Twig/Tests/TwigEngineTest.php b/src/Symfony/Bridge/Twig/Tests/TwigEngineTest.php index 3d15dae98f99..6f504cb399f3 100644 --- a/src/Symfony/Bridge/Twig/Tests/TwigEngineTest.php +++ b/src/Symfony/Bridge/Twig/Tests/TwigEngineTest.php @@ -13,9 +13,12 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\TwigEngine; +use Symfony\Component\Templating\TemplateNameParserInterface; use Symfony\Component\Templating\TemplateReference; use Twig\Environment; +use Twig\Error\SyntaxError; use Twig\Loader\ArrayLoader; +use Twig\Template; /** * @group legacy @@ -26,7 +29,7 @@ public function testExistsWithTemplateInstances() { $engine = $this->getTwig(); - $this->assertTrue($engine->exists($this->getMockForAbstractClass(\Twig\Template::class, [], '', false))); + $this->assertTrue($engine->exists($this->getMockForAbstractClass(Template::class, [], '', false))); } public function testExistsWithNonExistentTemplates() @@ -63,7 +66,7 @@ public function testRender() public function testRenderWithError() { - $this->expectException(\Twig\Error\SyntaxError::class); + $this->expectException(SyntaxError::class); $engine = $this->getTwig(); $engine->render(new TemplateReference('error')); @@ -75,7 +78,7 @@ protected function getTwig() 'index' => 'foo', 'error' => '{{ foo }', ])); - $parser = $this->getMockBuilder(\Symfony\Component\Templating\TemplateNameParserInterface::class)->getMock(); + $parser = $this->createMock(TemplateNameParserInterface::class); return new TwigEngine($twig, $parser); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/AnnotationsCacheWarmerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/AnnotationsCacheWarmerTest.php index 12e1d6fd9a65..ff03a6668800 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/AnnotationsCacheWarmerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/AnnotationsCacheWarmerTest.php @@ -125,7 +125,7 @@ public function testClassAutoloadExceptionWithUnrelatedException() */ private function getReadOnlyReader() { - $readerMock = $this->getMockBuilder(Reader::class)->getMock(); + $readerMock = $this->createMock(Reader::class); $readerMock->expects($this->exactly(0))->method('getClassAnnotations'); $readerMock->expects($this->exactly(0))->method('getClassAnnotation'); $readerMock->expects($this->exactly(0))->method('getMethodAnnotations'); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/TemplateFinderTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/TemplateFinderTest.php index 267fe7d7b91a..b81c9294259d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/TemplateFinderTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/TemplateFinderTest.php @@ -15,6 +15,7 @@ use Symfony\Bundle\FrameworkBundle\Templating\TemplateFilenameParser; use Symfony\Bundle\FrameworkBundle\Tests\Fixtures\BaseBundle\BaseBundle; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; +use Symfony\Component\HttpKernel\Kernel; /** * @group legacy @@ -23,12 +24,7 @@ class TemplateFinderTest extends TestCase { public function testFindAllTemplates() { - $kernel = $this - ->getMockBuilder(\Symfony\Component\HttpKernel\Kernel::class) - ->disableOriginalConstructor() - ->getMock() - ; - + $kernel = $this->createMock(Kernel::class); $kernel ->expects($this->any()) ->method('getBundle') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePoolDeleteCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePoolDeleteCommandTest.php index 796d004fdf61..907d5b9de363 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePoolDeleteCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePoolDeleteCommandTest.php @@ -17,6 +17,7 @@ use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; use Symfony\Component\Console\Tester\CommandTester; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\CacheClearer\Psr6CacheClearer; use Symfony\Component\HttpKernel\KernelInterface; @@ -26,8 +27,7 @@ class CachePoolDeleteCommandTest extends TestCase protected function setUp(): void { - $this->cachePool = $this->getMockBuilder(CacheItemPoolInterface::class) - ->getMock(); + $this->cachePool = $this->createMock(CacheItemPoolInterface::class); } public function testCommandWithValidKey() @@ -88,14 +88,9 @@ public function testCommandDeleteFailed() */ private function getKernel() { - $container = $this - ->getMockBuilder(\Symfony\Component\DependencyInjection\ContainerInterface::class) - ->getMock(); - - $kernel = $this - ->getMockBuilder(KernelInterface::class) - ->getMock(); + $container = $this->createMock(ContainerInterface::class); + $kernel = $this->createMock(KernelInterface::class); $kernel ->expects($this->any()) ->method('getContainer') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePruneCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePruneCommandTest.php index f8106d2ef1fa..3fe3a48e2fc0 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePruneCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePruneCommandTest.php @@ -18,6 +18,7 @@ use Symfony\Component\Cache\PruneableInterface; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\DependencyInjection\Argument\RewindableGenerator; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\KernelInterface; class CachePruneCommandTest extends TestCase @@ -54,14 +55,9 @@ private function getEmptyRewindableGenerator(): RewindableGenerator */ private function getKernel() { - $container = $this - ->getMockBuilder(\Symfony\Component\DependencyInjection\ContainerInterface::class) - ->getMock(); - - $kernel = $this - ->getMockBuilder(KernelInterface::class) - ->getMock(); + $container = $this->createMock(ContainerInterface::class); + $kernel = $this->createMock(KernelInterface::class); $kernel ->expects($this->any()) ->method('getContainer') @@ -80,10 +76,7 @@ private function getKernel() */ private function getPruneableInterfaceMock() { - $pruneable = $this - ->getMockBuilder(PruneableInterface::class) - ->getMock(); - + $pruneable = $this->createMock(PruneableInterface::class); $pruneable ->expects($this->atLeastOnce()) ->method('prune'); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterMatchCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterMatchCommandTest.php index ef59d07d7b17..f5af74b98ea5 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterMatchCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterMatchCommandTest.php @@ -16,10 +16,12 @@ use Symfony\Bundle\FrameworkBundle\Command\RouterMatchCommand; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Tester\CommandTester; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; +use Symfony\Component\Routing\RouterInterface; class RouterMatchCommandTest extends TestCase { @@ -55,7 +57,7 @@ private function getRouter() $routeCollection = new RouteCollection(); $routeCollection->add('foo', new Route('foo')); $requestContext = new RequestContext(); - $router = $this->getMockBuilder(\Symfony\Component\Routing\RouterInterface::class)->getMock(); + $router = $this->createMock(RouterInterface::class); $router ->expects($this->any()) ->method('getRouteCollection') @@ -70,7 +72,7 @@ private function getRouter() private function getKernel() { - $container = $this->getMockBuilder(\Symfony\Component\DependencyInjection\ContainerInterface::class)->getMock(); + $container = $this->createMock(ContainerInterface::class); $container ->expects($this->atLeastOnce()) ->method('has') @@ -85,7 +87,7 @@ private function getKernel() ->willReturn($this->getRouter()) ; - $kernel = $this->getMockBuilder(KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel ->expects($this->any()) ->method('getContainer') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php index 8f779bb42bc6..d013e1b40ba7 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php @@ -18,6 +18,11 @@ use Symfony\Component\DependencyInjection\Container; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpKernel; +use Symfony\Component\HttpKernel\Bundle\BundleInterface; +use Symfony\Component\HttpKernel\KernelInterface; +use Symfony\Component\Translation\Extractor\ExtractorInterface; +use Symfony\Component\Translation\Reader\TranslationReader; +use Symfony\Component\Translation\Translator; class TranslationDebugCommandTest extends TestCase { @@ -101,7 +106,7 @@ public function testDebugCustomDirectory() { $this->fs->mkdir($this->translationDir.'/customDir/translations'); $this->fs->mkdir($this->translationDir.'/customDir/templates'); - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel->expects($this->once()) ->method('getBundle') ->with($this->equalTo($this->translationDir.'/customDir')) @@ -117,7 +122,7 @@ public function testDebugCustomDirectory() public function testDebugInvalidDirectory() { $this->expectException(\InvalidArgumentException::class); - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel->expects($this->once()) ->method('getBundle') ->with($this->equalTo('dir')) @@ -142,16 +147,13 @@ protected function tearDown(): void private function createCommandTester($extractedMessages = [], $loadedMessages = [], $kernel = null, array $transPaths = [], array $viewsPaths = []): CommandTester { - $translator = $this->getMockBuilder(\Symfony\Component\Translation\Translator::class) - ->disableOriginalConstructor() - ->getMock(); - + $translator = $this->createMock(Translator::class); $translator ->expects($this->any()) ->method('getFallbackLocales') ->willReturn(['en']); - $extractor = $this->getMockBuilder(\Symfony\Component\Translation\Extractor\ExtractorInterface::class)->getMock(); + $extractor = $this->createMock(ExtractorInterface::class); $extractor ->expects($this->any()) ->method('extract') @@ -161,7 +163,7 @@ function ($path, $catalogue) use ($extractedMessages) { } ); - $loader = $this->getMockBuilder(\Symfony\Component\Translation\Reader\TranslationReader::class)->getMock(); + $loader = $this->createMock(TranslationReader::class); $loader ->expects($this->any()) ->method('read') @@ -182,7 +184,7 @@ function ($path, $catalogue) use ($loadedMessages) { ['test', true, $this->getBundle('test')], ]; } - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel ->expects($this->any()) ->method('getBundle') @@ -212,7 +214,7 @@ function ($path, $catalogue) use ($loadedMessages) { private function getBundle($path) { - $bundle = $this->getMockBuilder(\Symfony\Component\HttpKernel\Bundle\BundleInterface::class)->getMock(); + $bundle = $this->createMock(BundleInterface::class); $bundle ->expects($this->any()) ->method('getPath') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationUpdateCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationUpdateCommandTest.php index 2e9ca1297e24..cdb438889e55 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationUpdateCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationUpdateCommandTest.php @@ -18,6 +18,12 @@ use Symfony\Component\DependencyInjection\Container; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpKernel; +use Symfony\Component\HttpKernel\Bundle\BundleInterface; +use Symfony\Component\HttpKernel\KernelInterface; +use Symfony\Component\Translation\Extractor\ExtractorInterface; +use Symfony\Component\Translation\Reader\TranslationReader; +use Symfony\Component\Translation\Translator; +use Symfony\Component\Translation\Writer\TranslationWriter; class TranslationUpdateCommandTest extends TestCase { @@ -152,18 +158,15 @@ protected function tearDown(): void /** * @return CommandTester */ - private function createCommandTester($extractedMessages = [], $loadedMessages = [], HttpKernel\KernelInterface $kernel = null, array $transPaths = [], array $viewsPaths = []) + private function createCommandTester($extractedMessages = [], $loadedMessages = [], KernelInterface $kernel = null, array $transPaths = [], array $viewsPaths = []) { - $translator = $this->getMockBuilder(\Symfony\Component\Translation\Translator::class) - ->disableOriginalConstructor() - ->getMock(); - + $translator = $this->createMock(Translator::class); $translator ->expects($this->any()) ->method('getFallbackLocales') ->willReturn(['en']); - $extractor = $this->getMockBuilder(\Symfony\Component\Translation\Extractor\ExtractorInterface::class)->getMock(); + $extractor = $this->createMock(ExtractorInterface::class); $extractor ->expects($this->any()) ->method('extract') @@ -175,7 +178,7 @@ function ($path, $catalogue) use ($extractedMessages) { } ); - $loader = $this->getMockBuilder(\Symfony\Component\Translation\Reader\TranslationReader::class)->getMock(); + $loader = $this->createMock(TranslationReader::class); $loader ->expects($this->any()) ->method('read') @@ -185,7 +188,7 @@ function ($path, $catalogue) use ($loadedMessages) { } ); - $writer = $this->getMockBuilder(\Symfony\Component\Translation\Writer\TranslationWriter::class)->getMock(); + $writer = $this->createMock(TranslationWriter::class); $writer ->expects($this->any()) ->method('getFormats') @@ -204,7 +207,7 @@ function ($path, $catalogue) use ($loadedMessages) { ['test', true, $this->getBundle('test')], ]; } - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel ->expects($this->any()) ->method('getBundle') @@ -233,7 +236,7 @@ function ($path, $catalogue) use ($loadedMessages) { private function getBundle($path) { - $bundle = $this->getMockBuilder(\Symfony\Component\HttpKernel\Bundle\BundleInterface::class)->getMock(); + $bundle = $this->createMock(BundleInterface::class); $bundle ->expects($this->any()) ->method('getPath') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/XliffLintCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/XliffLintCommandTest.php index 7d6783d9352c..48af23514d8d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/XliffLintCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/XliffLintCommandTest.php @@ -73,20 +73,14 @@ private function createCommandTester($application = null): CommandTester private function getKernelAwareApplicationMock() { - $kernel = $this->getMockBuilder(KernelInterface::class) - ->disableOriginalConstructor() - ->getMock(); - + $kernel = $this->createMock(KernelInterface::class); $kernel ->expects($this->once()) ->method('locateResource') ->with('@AppBundle/Resources') ->willReturn(sys_get_temp_dir().'/xliff-lint-test'); - $application = $this->getMockBuilder(Application::class) - ->disableOriginalConstructor() - ->getMock(); - + $application = $this->createMock(Application::class); $application ->expects($this->once()) ->method('getKernel') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/YamlLintCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/YamlLintCommandTest.php index 70312702465d..0644c45ddfba 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/YamlLintCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/YamlLintCommandTest.php @@ -120,20 +120,14 @@ private function createCommandTester($application = null): CommandTester private function getKernelAwareApplicationMock() { - $kernel = $this->getMockBuilder(KernelInterface::class) - ->disableOriginalConstructor() - ->getMock(); - + $kernel = $this->createMock(KernelInterface::class); $kernel ->expects($this->once()) ->method('locateResource') ->with('@AppBundle/Resources') ->willReturn(sys_get_temp_dir().'/yml-lint-test'); - $application = $this->getMockBuilder(Application::class) - ->disableOriginalConstructor() - ->getMock(); - + $application = $this->createMock(Application::class); $application ->expects($this->once()) ->method('getKernel') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Console/ApplicationTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Console/ApplicationTest.php index e4aae37843af..f7c66c50d0fc 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Console/ApplicationTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Console/ApplicationTest.php @@ -11,6 +11,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Console; +use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Bundle\FrameworkBundle\EventListener\SuggestMissingPackageSubscriber; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; @@ -23,14 +24,18 @@ use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Tester\ApplicationTester; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\HttpKernel\Bundle\Bundle; +use Symfony\Component\HttpKernel\Bundle\BundleInterface; use Symfony\Component\HttpKernel\KernelInterface; class ApplicationTest extends TestCase { public function testBundleInterfaceImplementation() { - $bundle = $this->getMockBuilder(\Symfony\Component\HttpKernel\Bundle\BundleInterface::class)->getMock(); + $bundle = $this->createMock(BundleInterface::class); $kernel = $this->getKernel([$bundle], true); @@ -110,7 +115,7 @@ public function testBundleCommandCanBeFoundByAlias() */ public function testBundleCommandsHaveRightContainer() { - $command = $this->getMockForAbstractClass(\Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand::class, ['foo'], '', true, true, true, ['setContainer']); + $command = $this->getMockForAbstractClass(ContainerAwareCommand::class, ['foo'], '', true, true, true, ['setContainer']); $command->setCode(function () {}); $command->expects($this->exactly(2))->method('setContainer'); @@ -149,7 +154,7 @@ public function testRunOnlyWarnsOnUnregistrableCommand() $container->register(ThrowingCommand::class, ThrowingCommand::class); $container->setParameter('console.command.ids', [ThrowingCommand::class => ThrowingCommand::class]); - $kernel = $this->getMockBuilder(KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel ->method('getBundles') ->willReturn([$this->createBundleMock( @@ -177,7 +182,7 @@ public function testRegistrationErrorsAreDisplayedOnCommandNotFound() $container = new ContainerBuilder(); $container->register('event_dispatcher', EventDispatcher::class); - $kernel = $this->getMockBuilder(KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel ->method('getBundles') ->willReturn([$this->createBundleMock( @@ -206,7 +211,7 @@ public function testRunOnlyWarnsOnUnregistrableCommandAtTheEnd() $container->register(ThrowingCommand::class, ThrowingCommand::class); $container->setParameter('console.command.ids', [ThrowingCommand::class => ThrowingCommand::class]); - $kernel = $this->getMockBuilder(KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel->expects($this->once())->method('boot'); $kernel ->method('getBundles') @@ -259,10 +264,10 @@ private function createEventForSuggestingPackages(string $command, array $altern private function getKernel(array $bundles, $useDispatcher = false) { - $container = $this->getMockBuilder(\Symfony\Component\DependencyInjection\ContainerInterface::class)->getMock(); + $container = $this->createMock(ContainerInterface::class); if ($useDispatcher) { - $dispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class)->getMock(); + $dispatcher = $this->createMock(EventDispatcherInterface::class); $dispatcher ->expects($this->atLeastOnce()) ->method('dispatch') @@ -287,7 +292,7 @@ private function getKernel(array $bundles, $useDispatcher = false) ->willReturnOnConsecutiveCalls([], []) ; - $kernel = $this->getMockBuilder(KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel->expects($this->once())->method('boot'); $kernel ->expects($this->any()) @@ -305,7 +310,7 @@ private function getKernel(array $bundles, $useDispatcher = false) private function createBundleMock(array $commands) { - $bundle = $this->getMockBuilder(\Symfony\Component\HttpKernel\Bundle\Bundle::class)->getMock(); + $bundle = $this->createMock(Bundle::class); $bundle ->expects($this->once()) ->method('registerCommands') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php index 15f7222ae062..ccaa415e1595 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php @@ -14,6 +14,7 @@ use Psr\Container\ContainerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\DependencyInjection\Container; +use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\ParameterBag\ContainerBag; use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; @@ -68,7 +69,7 @@ public function testGetParameter() public function testMissingParameterBag() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class); + $this->expectException(ServiceNotFoundException::class); $this->expectExceptionMessage('TestAbstractController::getParameter()" method is missing a parameter bag'); $container = new Container(); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php index dcf8a2f1deee..c3f0cd26a85e 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php @@ -14,7 +14,9 @@ use Composer\Autoload\ClassLoader; use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; +use Symfony\Component\HttpKernel\Bundle\BundleInterface; use Symfony\Component\HttpKernel\Kernel; +use Symfony\Component\HttpKernel\KernelInterface; /** * @group legacy @@ -151,7 +153,7 @@ private function createParser() 'FooBundle' => $this->getBundle('TestBundle\FooBundle', 'FooBundle'), ]; - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel ->expects($this->any()) ->method('getBundle') @@ -180,7 +182,7 @@ private function createParser() private function getBundle($namespace, $name) { - $bundle = $this->getMockBuilder(\Symfony\Component\HttpKernel\Bundle\BundleInterface::class)->getMock(); + $bundle = $this->createMock(BundleInterface::class); $bundle->expects($this->any())->method('getName')->willReturn($name); $bundle->expects($this->any())->method('getNamespace')->willReturn($namespace); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php index 17eaa278b30e..83a84cddfeef 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php @@ -32,7 +32,7 @@ public function testGetControllerOnContainerAware() $controller = $resolver->getController($request); - $this->assertInstanceOf(\Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController::class, $controller[0]); + $this->assertInstanceOf(ContainerAwareController::class, $controller[0]); $this->assertInstanceOf(ContainerInterface::class, $controller[0]->getContainer()); $this->assertSame('testAction', $controller[1]); } @@ -45,7 +45,7 @@ public function testGetControllerOnContainerAwareInvokable() $controller = $resolver->getController($request); - $this->assertInstanceOf(\Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController::class, $controller); + $this->assertInstanceOf(ContainerAwareController::class, $controller); $this->assertInstanceOf(ContainerInterface::class, $controller->getContainer()); } @@ -69,7 +69,7 @@ public function testGetControllerWithBundleNotation() $controller = $resolver->getController($request); - $this->assertInstanceOf(\Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController::class, $controller[0]); + $this->assertInstanceOf(ContainerAwareController::class, $controller[0]); $this->assertInstanceOf(ContainerInterface::class, $controller[0]->getContainer()); $this->assertSame('testAction', $controller[1]); } @@ -200,12 +200,12 @@ protected function createControllerResolver(LoggerInterface $logger = null, Psr1 protected function createMockParser() { - return $this->getMockBuilder(ControllerNameParser::class)->disableOriginalConstructor()->getMock(); + return $this->createMock(ControllerNameParser::class); } protected function createMockContainer() { - return $this->getMockBuilder(ContainerInterface::class)->getMock(); + return $this->createMock(ContainerInterface::class); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTraitTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTraitTest.php index bd000bd51e6d..a5392b0cc0e8 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTraitTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTraitTest.php @@ -12,23 +12,38 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Controller; use Doctrine\Persistence\ManagerRegistry; +use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\Form\Form; +use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormConfigInterface; +use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\HttpFoundation\BinaryFileResponse; +use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; +use Symfony\Component\HttpFoundation\Session\Session; +use Symfony\Component\HttpFoundation\StreamedResponse; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; +use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; +use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; +use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Core\User\User; +use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\WebLink\Link; +use Twig\Environment; abstract class ControllerTraitTest extends TestCase { @@ -43,7 +58,7 @@ public function testForward() $requestStack = new RequestStack(); $requestStack->push($request); - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $kernel->expects($this->once())->method('handle')->willReturnCallback(function (Request $request) { return new Response($request->getRequestFormat().'--'.$request->getLocale()); }); @@ -100,7 +115,7 @@ public function testGetUserWithEmptyContainer() private function getContainerWithTokenStorage($token = null): Container { - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorage::class); $tokenStorage ->expects($this->once()) ->method('getToken') @@ -126,7 +141,7 @@ public function testJsonWithSerializer() { $container = new Container(); - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer = $this->createMock(SerializerInterface::class); $serializer ->expects($this->once()) ->method('serialize') @@ -147,7 +162,7 @@ public function testJsonWithSerializerContextOverride() { $container = new Container(); - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer = $this->createMock(SerializerInterface::class); $serializer ->expects($this->once()) ->method('serialize') @@ -169,7 +184,7 @@ public function testJsonWithSerializerContextOverride() public function testFile() { $container = new Container(); - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $container->set('http_kernel', $kernel); $controller = $this->createController(); @@ -270,7 +285,7 @@ public function testFileFromPathWithCustomizedFileName() public function testFileWhichDoesNotExist() { - $this->expectException(\Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException::class); + $this->expectException(FileNotFoundException::class); $controller = $this->createController(); $controller->file('some-file.txt', 'test.php'); @@ -278,7 +293,7 @@ public function testFileWhichDoesNotExist() public function testIsGranted() { - $authorizationChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface::class)->getMock(); + $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class); $authorizationChecker->expects($this->once())->method('isGranted')->willReturn(true); $container = new Container(); @@ -292,8 +307,8 @@ public function testIsGranted() public function testdenyAccessUnlessGranted() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AccessDeniedException::class); - $authorizationChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface::class)->getMock(); + $this->expectException(AccessDeniedException::class); + $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class); $authorizationChecker->expects($this->once())->method('isGranted')->willReturn(false); $container = new Container(); @@ -307,7 +322,7 @@ public function testdenyAccessUnlessGranted() public function testRenderViewTwig() { - $twig = $this->getMockBuilder(\Twig\Environment::class)->disableOriginalConstructor()->getMock(); + $twig = $this->createMock(Environment::class); $twig->expects($this->once())->method('render')->willReturn('bar'); $container = new Container(); @@ -321,7 +336,7 @@ public function testRenderViewTwig() public function testRenderTwig() { - $twig = $this->getMockBuilder(\Twig\Environment::class)->disableOriginalConstructor()->getMock(); + $twig = $this->createMock(Environment::class); $twig->expects($this->once())->method('render')->willReturn('bar'); $container = new Container(); @@ -335,7 +350,7 @@ public function testRenderTwig() public function testStreamTwig() { - $twig = $this->getMockBuilder(\Twig\Environment::class)->disableOriginalConstructor()->getMock(); + $twig = $this->createMock(Environment::class); $container = new Container(); $container->set('twig', $twig); @@ -343,12 +358,12 @@ public function testStreamTwig() $controller = $this->createController(); $controller->setContainer($container); - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\StreamedResponse::class, $controller->stream('foo')); + $this->assertInstanceOf(StreamedResponse::class, $controller->stream('foo')); } public function testRedirectToRoute() { - $router = $this->getMockBuilder(\Symfony\Component\Routing\RouterInterface::class)->getMock(); + $router = $this->createMock(RouterInterface::class); $router->expects($this->once())->method('generate')->willReturn('/foo'); $container = new Container(); @@ -358,7 +373,7 @@ public function testRedirectToRoute() $controller->setContainer($container); $response = $controller->redirectToRoute('foo'); - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\RedirectResponse::class, $response); + $this->assertInstanceOf(RedirectResponse::class, $response); $this->assertSame('/foo', $response->getTargetUrl()); $this->assertSame(302, $response->getStatusCode()); } @@ -369,7 +384,7 @@ public function testRedirectToRoute() public function testAddFlash() { $flashBag = new FlashBag(); - $session = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\Session::class)->getMock(); + $session = $this->createMock(Session::class); $session->expects($this->once())->method('getFlashBag')->willReturn($flashBag); $container = new Container(); @@ -386,12 +401,12 @@ public function testCreateAccessDeniedException() { $controller = $this->createController(); - $this->assertInstanceOf(\Symfony\Component\Security\Core\Exception\AccessDeniedException::class, $controller->createAccessDeniedException()); + $this->assertInstanceOf(AccessDeniedException::class, $controller->createAccessDeniedException()); } public function testIsCsrfTokenValid() { - $tokenManager = $this->getMockBuilder(\Symfony\Component\Security\Csrf\CsrfTokenManagerInterface::class)->getMock(); + $tokenManager = $this->createMock(CsrfTokenManagerInterface::class); $tokenManager->expects($this->once())->method('isTokenValid')->willReturn(true); $container = new Container(); @@ -405,7 +420,7 @@ public function testIsCsrfTokenValid() public function testGenerateUrl() { - $router = $this->getMockBuilder(\Symfony\Component\Routing\RouterInterface::class)->getMock(); + $router = $this->createMock(RouterInterface::class); $router->expects($this->once())->method('generate')->willReturn('/foo'); $container = new Container(); @@ -422,7 +437,7 @@ public function testRedirect() $controller = $this->createController(); $response = $controller->redirect('https://dunglas.fr', 301); - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\RedirectResponse::class, $response); + $this->assertInstanceOf(RedirectResponse::class, $response); $this->assertSame('https://dunglas.fr', $response->getTargetUrl()); $this->assertSame(301, $response->getStatusCode()); } @@ -432,7 +447,7 @@ public function testRedirect() */ public function testRenderViewTemplating() { - $templating = $this->getMockBuilder(\Symfony\Bundle\FrameworkBundle\Templating\EngineInterface::class)->getMock(); + $templating = $this->createMock(EngineInterface::class); $templating->expects($this->once())->method('render')->willReturn('bar'); $container = new Container(); @@ -449,7 +464,7 @@ public function testRenderViewTemplating() */ public function testRenderTemplating() { - $templating = $this->getMockBuilder(\Symfony\Bundle\FrameworkBundle\Templating\EngineInterface::class)->getMock(); + $templating = $this->createMock(EngineInterface::class); $templating->expects($this->once())->method('render')->willReturn('bar'); $container = new Container(); @@ -466,7 +481,7 @@ public function testRenderTemplating() */ public function testStreamTemplating() { - $templating = $this->getMockBuilder(\Symfony\Bundle\FrameworkBundle\Templating\EngineInterface::class)->getMock(); + $templating = $this->createMock(EngineInterface::class); $container = new Container(); $container->set('templating', $templating); @@ -474,21 +489,21 @@ public function testStreamTemplating() $controller = $this->createController(); $controller->setContainer($container); - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\StreamedResponse::class, $controller->stream('foo')); + $this->assertInstanceOf(StreamedResponse::class, $controller->stream('foo')); } public function testCreateNotFoundException() { $controller = $this->createController(); - $this->assertInstanceOf(\Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class, $controller->createNotFoundException()); + $this->assertInstanceOf(NotFoundHttpException::class, $controller->createNotFoundException()); } public function testCreateForm() { - $form = new Form($this->getMockBuilder(FormConfigInterface::class)->getMock()); + $form = new Form($this->createMock(FormConfigInterface::class)); - $formFactory = $this->getMockBuilder(\Symfony\Component\Form\FormFactoryInterface::class)->getMock(); + $formFactory = $this->createMock(FormFactoryInterface::class); $formFactory->expects($this->once())->method('create')->willReturn($form); $container = new Container(); @@ -502,9 +517,9 @@ public function testCreateForm() public function testCreateFormBuilder() { - $formBuilder = $this->getMockBuilder(\Symfony\Component\Form\FormBuilderInterface::class)->getMock(); + $formBuilder = $this->createMock(FormBuilderInterface::class); - $formFactory = $this->getMockBuilder(\Symfony\Component\Form\FormFactoryInterface::class)->getMock(); + $formFactory = $this->createMock(FormFactoryInterface::class); $formFactory->expects($this->once())->method('createBuilder')->willReturn($formBuilder); $container = new Container(); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php index f053af3fa435..70ccf7c97cf5 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php @@ -85,7 +85,7 @@ public function testRoute($permanent, $keepRequestMethod, $keepQueryParams, $ign $request->attributes = new ParameterBag($attributes); - $router = $this->getMockBuilder(UrlGeneratorInterface::class)->getMock(); + $router = $this->createMock(UrlGeneratorInterface::class); $router ->expects($this->exactly(2)) ->method('generate') @@ -304,7 +304,7 @@ public function testRedirectWithQuery() $request = $this->createRequestObject($scheme, $host, $port, $baseUrl, 'b.se=zaza&f[%2525][%26][%3D][p.c]=d'); $request->attributes = new ParameterBag(['_route_params' => ['base2' => 'zaza']]); - $urlGenerator = $this->getMockBuilder(UrlGeneratorInterface::class)->getMock(); + $urlGenerator = $this->createMock(UrlGeneratorInterface::class); $urlGenerator->expects($this->exactly(2)) ->method('generate') ->willReturn('/test?b.se=zaza&base2=zaza&f[%2525][%26][%3D][p.c]=d') @@ -326,7 +326,7 @@ public function testRedirectWithQueryWithRouteParamsOveriding() $request = $this->createRequestObject($scheme, $host, $port, $baseUrl, 'b.se=zaza'); $request->attributes = new ParameterBag(['_route_params' => ['b.se' => 'zouzou']]); - $urlGenerator = $this->getMockBuilder(UrlGeneratorInterface::class)->getMock(); + $urlGenerator = $this->createMock(UrlGeneratorInterface::class); $urlGenerator->expects($this->exactly(2))->method('generate')->willReturn('/test?b.se=zouzou')->with('/test', ['b.se' => 'zouzou'], UrlGeneratorInterface::ABSOLUTE_URL); $controller = new RedirectController($urlGenerator); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php index b746492bf510..4230797b07d3 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php @@ -14,6 +14,7 @@ use Symfony\Bundle\FrameworkBundle\Controller\TemplateController; use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; +use Twig\Environment; /** * @author Kévin Dunglas @@ -22,7 +23,7 @@ class TemplateControllerTest extends TestCase { public function testTwig() { - $twig = $this->getMockBuilder(\Twig\Environment::class)->disableOriginalConstructor()->getMock(); + $twig = $this->createMock(Environment::class); $twig->expects($this->exactly(2))->method('render')->willReturn('bar'); $controller = new TemplateController($twig); @@ -36,7 +37,7 @@ public function testTwig() */ public function testTemplating() { - $templating = $this->getMockBuilder(EngineInterface::class)->getMock(); + $templating = $this->createMock(EngineInterface::class); $templating->expects($this->exactly(2))->method('render')->willReturn('bar'); $controller = new TemplateController(null, $templating); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPrunerPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPrunerPassTest.php index 44c2909cf6b8..c2494d9cb2ec 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPrunerPassTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPrunerPassTest.php @@ -17,6 +17,7 @@ use Symfony\Component\Cache\Adapter\PhpFilesAdapter; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Reference; /** @@ -61,7 +62,7 @@ public function testCompilePassIsIgnoredIfCommandDoesNotExist() public function testCompilerPassThrowsOnInvalidDefinitionClass() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Class "Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\NotFound" used for service "pool.not-found" cannot be found.'); $container = new ContainerBuilder(); $container->register('console.command.cache_pool_prune')->addArgument([]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php index 32ca95903201..6b12a00bb938 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\WorkflowGuardListenerPass; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\LogicException; use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; @@ -54,7 +55,7 @@ public function testNoExeptionIfAllDependenciesArePresent() public function testExceptionIfTheTokenStorageServiceIsNotPresent() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('The "security.token_storage" service is needed to be able to use the workflow guard listener.'); $this->container->setParameter('workflow.has_guard_listeners', true); $this->container->register('security.authorization_checker', AuthorizationCheckerInterface::class); @@ -66,7 +67,7 @@ public function testExceptionIfTheTokenStorageServiceIsNotPresent() public function testExceptionIfTheAuthorizationCheckerServiceIsNotPresent() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('The "security.authorization_checker" service is needed to be able to use the workflow guard listener.'); $this->container->setParameter('workflow.has_guard_listeners', true); $this->container->register('security.token_storage', TokenStorageInterface::class); @@ -78,7 +79,7 @@ public function testExceptionIfTheAuthorizationCheckerServiceIsNotPresent() public function testExceptionIfTheAuthenticationTrustResolverServiceIsNotPresent() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('The "security.authentication.trust_resolver" service is needed to be able to use the workflow guard listener.'); $this->container->setParameter('workflow.has_guard_listeners', true); $this->container->register('security.token_storage', TokenStorageInterface::class); @@ -90,7 +91,7 @@ public function testExceptionIfTheAuthenticationTrustResolverServiceIsNotPresent public function testExceptionIfTheRoleHierarchyServiceIsNotPresent() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('The "security.role_hierarchy" service is needed to be able to use the workflow guard listener.'); $this->container->setParameter('workflow.has_guard_listeners', true); $this->container->register('security.token_storage', TokenStorageInterface::class); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php index 7f6d8413154d..de4875653340 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php @@ -27,6 +27,7 @@ use Symfony\Component\Cache\Adapter\ProxyAdapter; use Symfony\Component\Cache\Adapter\RedisAdapter; use Symfony\Component\Cache\DependencyInjection\CachePoolPass; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Compiler\ResolveInstanceofConditionalsPass; @@ -37,10 +38,12 @@ use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\Form\Form; use Symfony\Component\HttpClient\ScopingHttpClient; use Symfony\Component\HttpKernel\DependencyInjection\LoggerPass; use Symfony\Component\Messenger\Transport\TransportFactory; use Symfony\Component\PropertyAccess\PropertyAccessor; +use Symfony\Component\Security\Core\Security; use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader; use Symfony\Component\Serializer\Mapping\Loader\XmlFileLoader; use Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader; @@ -54,7 +57,10 @@ use Symfony\Component\Validator\DependencyInjection\AddConstraintValidatorsPass; use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader; use Symfony\Component\Validator\Util\LegacyTranslatorProxy; +use Symfony\Component\Validator\Validation; +use Symfony\Component\Validator\Validator\ValidatorInterface; use Symfony\Component\Workflow; +use Symfony\Component\Workflow\Exception\InvalidDefinitionException; use Symfony\Component\Workflow\Metadata\InMemoryMetadataStore; use Symfony\Contracts\Translation\TranslatorInterface; @@ -331,28 +337,28 @@ public function testWorkflowLegacy() public function testWorkflowAreValidated() { - $this->expectException(\Symfony\Component\Workflow\Exception\InvalidDefinitionException::class); + $this->expectException(InvalidDefinitionException::class); $this->expectExceptionMessage('A transition from a place/state must have an unique name. Multiple transitions named "go" from place/state "first" were found on StateMachine "my_workflow".'); $this->createContainerFromFile('workflow_not_valid'); } public function testWorkflowCannotHaveBothTypeAndService() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('"type" and "service" cannot be used together.'); $this->createContainerFromFile('workflow_legacy_with_type_and_service'); } public function testWorkflowCannotHaveBothSupportsAndSupportStrategy() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('"supports" and "support_strategy" cannot be used together.'); $this->createContainerFromFile('workflow_with_support_and_support_strategy'); } public function testWorkflowShouldHaveOneOfSupportsAndSupportStrategy() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('"supports" or "support_strategy" should be configured.'); $this->createContainerFromFile('workflow_without_support_and_support_strategy'); } @@ -362,7 +368,7 @@ public function testWorkflowShouldHaveOneOfSupportsAndSupportStrategy() */ public function testWorkflowCannotHaveBothArgumentsAndService() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('"arguments" and "service" cannot be used together.'); $this->createContainerFromFile('workflow_legacy_with_arguments_and_service'); } @@ -524,7 +530,7 @@ public function testRouter() public function testRouterRequiresResourceOption() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $container = $this->createContainer(); $loader = new FrameworkExtension(); $loader->load([['router' => true]], $container); @@ -838,19 +844,19 @@ public function testTranslator() $this->assertSame($container->getParameter('kernel.cache_dir').'/translations', $options['cache_dir']); $files = array_map('realpath', $options['resource_files']['en']); - $ref = new \ReflectionClass(\Symfony\Component\Validator\Validation::class); + $ref = new \ReflectionClass(Validation::class); $this->assertContains( strtr(\dirname($ref->getFileName()).'/Resources/translations/validators.en.xlf', '/', \DIRECTORY_SEPARATOR), $files, '->registerTranslatorConfiguration() finds Validator translation resources' ); - $ref = new \ReflectionClass(\Symfony\Component\Form\Form::class); + $ref = new \ReflectionClass(Form::class); $this->assertContains( strtr(\dirname($ref->getFileName()).'/Resources/translations/validators.en.xlf', '/', \DIRECTORY_SEPARATOR), $files, '->registerTranslatorConfiguration() finds Form translation resources' ); - $ref = new \ReflectionClass(\Symfony\Component\Security\Core\Security::class); + $ref = new \ReflectionClass(Security::class); $this->assertContains( strtr(\dirname($ref->getFileName()).'/Resources/translations/security.en.xlf', '/', \DIRECTORY_SEPARATOR), $files, @@ -921,7 +927,7 @@ public function testTranslatorCacheDirDisabled() */ public function testTemplatingRequiresAtLeastOneEngine() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $container = $this->createContainer(); $loader = new FrameworkExtension(); $loader->load([['templating' => null]], $container); @@ -932,7 +938,7 @@ public function testValidation() $container = $this->createContainerFromFile('full'); $projectDir = $container->getParameter('kernel.project_dir'); - $ref = new \ReflectionClass(\Symfony\Component\Form\Form::class); + $ref = new \ReflectionClass(Form::class); $xmlMappings = [ \dirname($ref->getFileName()).'/Resources/config/validation.xml', strtr($projectDir.'/config/validator/foo.xml', '/', \DIRECTORY_SEPARATOR), @@ -969,7 +975,7 @@ public function testValidationService() { $container = $this->createContainerFromFile('validation_annotations', ['kernel.charset' => 'UTF-8'], false); - $this->assertInstanceOf(\Symfony\Component\Validator\Validator\ValidatorInterface::class, $container->get('validator')); + $this->assertInstanceOf(ValidatorInterface::class, $container->get('validator')); } public function testAnnotations() @@ -1097,7 +1103,7 @@ public function testValidationNoStaticMethod() */ public function testCannotConfigureStrictEmailAndEmailValidationModeAtTheSameTime() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('"strict_email" and "email_validation_mode" cannot be used together.'); $this->createContainerFromFile('validation_strict_email_and_validation_mode'); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php index 0212e662c3d4..1c69d35e4e81 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php @@ -14,6 +14,7 @@ use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; +use Symfony\Component\Workflow\Exception\InvalidDefinitionException; class PhpFrameworkExtensionTest extends FrameworkExtensionTest { @@ -55,7 +56,7 @@ public function testAssetPackageCannotHavePathAndUrl() public function testWorkflowValidationStateMachine() { - $this->expectException(\Symfony\Component\Workflow\Exception\InvalidDefinitionException::class); + $this->expectException(InvalidDefinitionException::class); $this->expectExceptionMessage('A transition from a place/state must have an unique name. Multiple transitions named "a_to_b" from place/state "a" were found on StateMachine "article".'); $this->createContainerFromClosure(function ($container) { $container->loadFromExtension('framework', [ @@ -157,7 +158,7 @@ public function testWorkflowValidationMultipleState() */ public function testWorkflowValidationSingleState() { - $this->expectException(\Symfony\Component\Workflow\Exception\InvalidDefinitionException::class); + $this->expectException(InvalidDefinitionException::class); $this->expectExceptionMessage('The marking store of workflow "article" can not store many places. But the transition "a_to_b" has too many output (2). Only one is accepted.'); $this->createContainerFromClosure(function ($container) { $container->loadFromExtension('framework', [ diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/EventListener/ResolveControllerNameSubscriberTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/EventListener/ResolveControllerNameSubscriberTest.php index 362f00e95c29..2aa519acfb2b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/EventListener/ResolveControllerNameSubscriberTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/EventListener/ResolveControllerNameSubscriberTest.php @@ -26,12 +26,12 @@ class ResolveControllerNameSubscriberTest extends TestCase { public function testReplacesControllerAttribute() { - $parser = $this->getMockBuilder(ControllerNameParser::class)->disableOriginalConstructor()->getMock(); + $parser = $this->createMock(ControllerNameParser::class); $parser->expects($this->any()) ->method('parse') ->with('AppBundle:Starting:format') ->willReturn('App\\Final\\Format::methodName'); - $httpKernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $httpKernel = $this->createMock(HttpKernelInterface::class); $request = new Request(); $request->attributes->set('_controller', 'AppBundle:Starting:format'); @@ -50,10 +50,10 @@ public function testReplacesControllerAttribute() */ public function testSkipsOtherControllerFormats($controller) { - $parser = $this->getMockBuilder(ControllerNameParser::class)->disableOriginalConstructor()->getMock(); + $parser = $this->createMock(ControllerNameParser::class); $parser->expects($this->never()) ->method('parse'); - $httpKernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $httpKernel = $this->createMock(HttpKernelInterface::class); $request = new Request(); $request->attributes->set('_controller', $controller); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolClearCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolClearCommandTest.php index c3f56f1e4db4..a3a0b2313613 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolClearCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolClearCommandTest.php @@ -14,6 +14,7 @@ use Symfony\Bundle\FrameworkBundle\Command\CachePoolClearCommand; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Tester\CommandTester; +use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; /** * @group functional @@ -67,7 +68,7 @@ public function testCallClearer() public function testClearUnexistingPool() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class); + $this->expectException(ServiceNotFoundException::class); $this->expectExceptionMessage('You have requested a non-existent service "unknown_pool"'); $this->createCommandTester() ->execute(['pools' => ['unknown_pool']], ['decorated' => false]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/DelegatingLoaderTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/DelegatingLoaderTest.php index daed030f721a..ce0f08b4e212 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/DelegatingLoaderTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/DelegatingLoaderTest.php @@ -10,6 +10,7 @@ use Symfony\Component\Config\Loader\LoaderResolverInterface; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; +use Symfony\Component\Routing\RouteCompiler; class DelegatingLoaderTest extends TestCase { @@ -19,20 +20,16 @@ class DelegatingLoaderTest extends TestCase */ public function testConstructorApi() { - $controllerNameParser = $this->getMockBuilder(ControllerNameParser::class) - ->disableOriginalConstructor() - ->getMock(); + $controllerNameParser = $this->createMock(ControllerNameParser::class); new DelegatingLoader($controllerNameParser, new LoaderResolver()); $this->assertTrue(true, '__construct() takes a ControllerNameParser and LoaderResolverInterface respectively as its first and second argument.'); } public function testLoadDefaultOptions() { - $loaderResolver = $this->getMockBuilder(LoaderResolverInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $loaderResolver = $this->createMock(LoaderResolverInterface::class); - $loader = $this->getMockBuilder(LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loaderResolver->expects($this->once()) ->method('resolve') @@ -52,13 +49,13 @@ public function testLoadDefaultOptions() $this->assertCount(2, $loadedRouteCollection); $expected = [ - 'compiler_class' => 'Symfony\Component\Routing\RouteCompiler', + 'compiler_class' => RouteCompiler::class, 'utf8' => false, ]; $this->assertSame($expected, $routeCollection->get('foo')->getOptions()); $expected = [ - 'compiler_class' => 'Symfony\Component\Routing\RouteCompiler', + 'compiler_class' => RouteCompiler::class, 'foo' => 123, 'utf8' => true, ]; @@ -71,20 +68,15 @@ public function testLoadDefaultOptions() */ public function testLoad() { - $controllerNameParser = $this->getMockBuilder(ControllerNameParser::class) - ->disableOriginalConstructor() - ->getMock(); - + $controllerNameParser = $this->createMock(ControllerNameParser::class); $controllerNameParser->expects($this->once()) ->method('parse') ->with('foo:bar:baz') ->willReturn('some_parsed::controller'); - $loaderResolver = $this->getMockBuilder(LoaderResolverInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $loaderResolver = $this->createMock(LoaderResolverInterface::class); - $loader = $this->getMockBuilder(LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loaderResolver->expects($this->once()) ->method('resolve') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RouterTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RouterTest.php index 6cf4cf3fad69..ca66001ed9fa 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RouterTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RouterTest.php @@ -17,6 +17,7 @@ use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\Config\ContainerParametersResource; use Symfony\Component\DependencyInjection\Container; +use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; @@ -375,7 +376,7 @@ public function testHostPlaceholdersWithSfContainer() public function testExceptionOnNonExistentParameterWithSfContainer() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException::class); + $this->expectException(ParameterNotFoundException::class); $this->expectExceptionMessage('You have requested a non-existent parameter "nope".'); $routes = new RouteCollection(); @@ -504,7 +505,7 @@ public function getNonStringValues() private function getServiceContainer(RouteCollection $routes): Container { - $loader = $this->getMockBuilder(LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loader ->expects($this->any()) @@ -525,7 +526,7 @@ private function getServiceContainer(RouteCollection $routes): Container private function getPsr11ServiceContainer(RouteCollection $routes): ContainerInterface { - $loader = $this->getMockBuilder(LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loader ->expects($this->any()) @@ -533,7 +534,7 @@ private function getPsr11ServiceContainer(RouteCollection $routes): ContainerInt ->willReturn($routes) ; - $sc = $this->getMockBuilder(ContainerInterface::class)->getMock(); + $sc = $this->createMock(ContainerInterface::class); $sc ->expects($this->once()) @@ -546,7 +547,7 @@ private function getPsr11ServiceContainer(RouteCollection $routes): ContainerInt private function getParameterBag(array $params = []): ContainerInterface { - $bag = $this->getMockBuilder(ContainerInterface::class)->getMock(); + $bag = $this->createMock(ContainerInterface::class); $bag ->expects($this->any()) ->method('get') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/DelegatingEngineTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/DelegatingEngineTest.php index 344920d85127..c26d90770f6b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/DelegatingEngineTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/DelegatingEngineTest.php @@ -15,6 +15,7 @@ use Symfony\Bundle\FrameworkBundle\Templating\DelegatingEngine; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\Templating\EngineInterface; /** * @group legacy @@ -88,7 +89,7 @@ public function testRenderResponseWithTemplatingEngine() private function getEngineMock($template, $supports) { - $engine = $this->getMockBuilder(\Symfony\Component\Templating\EngineInterface::class)->getMock(); + $engine = $this->createMock(EngineInterface::class); $engine->expects($this->once()) ->method('supports') @@ -100,7 +101,7 @@ private function getEngineMock($template, $supports) private function getFrameworkEngineMock($template, $supports) { - $engine = $this->getMockBuilder(\Symfony\Bundle\FrameworkBundle\Templating\EngineInterface::class)->getMock(); + $engine = $this->createMock(\Symfony\Bundle\FrameworkBundle\Templating\EngineInterface::class); $engine->expects($this->once()) ->method('supports') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/GlobalVariablesTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/GlobalVariablesTest.php index 5795b2528f83..cb50a6cbae0c 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/GlobalVariablesTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/GlobalVariablesTest.php @@ -14,6 +14,9 @@ use Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; use Symfony\Component\DependencyInjection\Container; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; +use Symfony\Component\Security\Core\User\UserInterface; /** * @group legacy @@ -36,14 +39,14 @@ public function testGetTokenNoTokenStorage() public function testGetTokenNoToken() { - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $this->container->set('security.token_storage', $tokenStorage); $this->assertNull($this->globals->getToken()); } public function testGetToken() { - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $this->container->set('security.token_storage', $tokenStorage); @@ -62,7 +65,7 @@ public function testGetUserNoTokenStorage() public function testGetUserNoToken() { - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $this->container->set('security.token_storage', $tokenStorage); $this->assertNull($this->globals->getUser()); } @@ -72,8 +75,8 @@ public function testGetUserNoToken() */ public function testGetUser($user, $expectedUser) { - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); + $token = $this->createMock(TokenInterface::class); $this->container->set('security.token_storage', $tokenStorage); @@ -92,9 +95,9 @@ public function testGetUser($user, $expectedUser) public function getUserProvider() { - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $std = new \stdClass(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); return [ [$user, $user], diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php index 2e2e449327ed..33ea9f380f90 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php @@ -11,6 +11,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper; +use Symfony\Bundle\FrameworkBundle\FrameworkBundle; use Symfony\Bundle\FrameworkBundle\Templating\Helper\TranslatorHelper; use Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper\Fixtures\StubTemplateNameParser; use Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper\Fixtures\StubTranslator; @@ -36,7 +37,7 @@ protected function getExtensions() { // should be moved to the Form component once absolute file paths are supported // by the default name parser in the Templating component - $reflClass = new \ReflectionClass(\Symfony\Bundle\FrameworkBundle\FrameworkBundle::class); + $reflClass = new \ReflectionClass(FrameworkBundle::class); $root = realpath(\dirname($reflClass->getFileName()).'/Resources/views'); $rootTheme = realpath(__DIR__.'/Resources'); $templateNameParser = new StubTemplateNameParser($root, $rootTheme); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php index 6bc09530e6bd..f985efce55dc 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php @@ -11,6 +11,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper; +use Symfony\Bundle\FrameworkBundle\FrameworkBundle; use Symfony\Bundle\FrameworkBundle\Templating\Helper\TranslatorHelper; use Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper\Fixtures\StubTemplateNameParser; use Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper\Fixtures\StubTranslator; @@ -80,7 +81,7 @@ protected function getExtensions() { // should be moved to the Form component once absolute file paths are supported // by the default name parser in the Templating component - $reflClass = new \ReflectionClass(\Symfony\Bundle\FrameworkBundle\FrameworkBundle::class); + $reflClass = new \ReflectionClass(FrameworkBundle::class); $root = realpath(\dirname($reflClass->getFileName()).'/Resources/views'); $rootTheme = realpath(__DIR__.'/Resources'); $templateNameParser = new StubTemplateNameParser($root, $rootTheme); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/StopwatchHelperTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/StopwatchHelperTest.php index 3794e047b9e4..074916ed7515 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/StopwatchHelperTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/StopwatchHelperTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Bundle\FrameworkBundle\Templating\Helper\StopwatchHelper; +use Symfony\Component\Stopwatch\Stopwatch; /** * @group legacy @@ -21,7 +22,7 @@ class StopwatchHelperTest extends TestCase { public function testDevEnvironment() { - $stopwatch = $this->getMockBuilder(\Symfony\Component\Stopwatch\Stopwatch::class)->getMock(); + $stopwatch = $this->createMock(Stopwatch::class); $stopwatch->expects($this->once()) ->method('start') ->with('foo'); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Loader/TemplateLocatorTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Loader/TemplateLocatorTest.php index fe66fda7aaf5..5e0cea2cd12c 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Loader/TemplateLocatorTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Loader/TemplateLocatorTest.php @@ -14,6 +14,7 @@ use Symfony\Bundle\FrameworkBundle\Templating\Loader\TemplateLocator; use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; +use Symfony\Component\Config\FileLocator; /** * @group legacy @@ -90,7 +91,7 @@ public function testThrowsAnExceptionWhenTemplateIsNotATemplateReferenceInterfac protected function getFileLocator() { return $this - ->getMockBuilder(\Symfony\Component\Config\FileLocator::class) + ->getMockBuilder(FileLocator::class) ->setMethods(['locate']) ->setConstructorArgs(['/path/to/fallback']) ->getMock() diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/PhpEngineTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/PhpEngineTest.php index 2f1a19cc68bb..8c39fb08279d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/PhpEngineTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/PhpEngineTest.php @@ -19,6 +19,7 @@ use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; +use Symfony\Component\Templating\Loader\Loader; use Symfony\Component\Templating\TemplateNameParser; /** @@ -29,7 +30,7 @@ class PhpEngineTest extends TestCase public function testEvaluateAddsAppGlobal() { $container = $this->getContainer(); - $loader = $this->getMockForAbstractClass(\Symfony\Component\Templating\Loader\Loader::class); + $loader = $this->getMockForAbstractClass(Loader::class); $engine = new PhpEngine(new TemplateNameParser(), $container, $loader, $app = new GlobalVariables($container)); $globals = $engine->getGlobals(); $this->assertSame($app, $globals['app']); @@ -38,7 +39,7 @@ public function testEvaluateAddsAppGlobal() public function testEvaluateWithoutAvailableRequest() { $container = new Container(); - $loader = $this->getMockForAbstractClass(\Symfony\Component\Templating\Loader\Loader::class); + $loader = $this->getMockForAbstractClass(Loader::class); $engine = new PhpEngine(new TemplateNameParser(), $container, $loader, new GlobalVariables($container)); $this->assertFalse($container->has('request_stack')); @@ -50,7 +51,7 @@ public function testGetInvalidHelper() { $this->expectException(\InvalidArgumentException::class); $container = $this->getContainer(); - $loader = $this->getMockForAbstractClass(\Symfony\Component\Templating\Loader\Loader::class); + $loader = $this->getMockForAbstractClass(Loader::class); $engine = new PhpEngine(new TemplateNameParser(), $container, $loader); $engine->get('non-existing-helper'); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php index 76fc7b91bc45..4fe8aa3a4367 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php @@ -14,6 +14,7 @@ use Symfony\Bundle\FrameworkBundle\Templating\TemplateNameParser; use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; +use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Templating\TemplateReference as BaseTemplateReference; /** @@ -25,7 +26,7 @@ class TemplateNameParserTest extends TestCase protected function setUp(): void { - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel ->expects($this->any()) ->method('getBundle') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TimedPhpEngineTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TimedPhpEngineTest.php index ed7d87b30538..86c6d3940c71 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TimedPhpEngineTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TimedPhpEngineTest.php @@ -20,6 +20,7 @@ use Symfony\Component\Templating\Loader\Loader; use Symfony\Component\Templating\Storage\StringStorage; use Symfony\Component\Templating\TemplateNameParserInterface; +use Symfony\Component\Templating\TemplateReferenceInterface; /** * @group legacy @@ -49,13 +50,13 @@ public function testThatRenderLogsTime() private function getContainer(): Container { - return $this->getMockBuilder(Container::class)->getMock(); + return $this->createMock(Container::class); } private function getTemplateNameParser(): TemplateNameParserInterface { - $templateReference = $this->getMockBuilder(\Symfony\Component\Templating\TemplateReferenceInterface::class)->getMock(); - $templateNameParser = $this->getMockBuilder(TemplateNameParserInterface::class)->getMock(); + $templateReference = $this->createMock(TemplateReferenceInterface::class); + $templateNameParser = $this->createMock(TemplateNameParserInterface::class); $templateNameParser->expects($this->any()) ->method('parse') ->willReturn($templateReference); @@ -65,9 +66,7 @@ private function getTemplateNameParser(): TemplateNameParserInterface private function getGlobalVariables(): GlobalVariables { - return $this->getMockBuilder(GlobalVariables::class) - ->disableOriginalConstructor() - ->getMock(); + return $this->createMock(GlobalVariables::class); } private function getStorage(): StringStorage @@ -92,13 +91,11 @@ private function getLoader($storage): Loader private function getStopwatchEvent(): StopwatchEvent { - return $this->getMockBuilder(StopwatchEvent::class) - ->disableOriginalConstructor() - ->getMock(); + return $this->createMock(StopwatchEvent::class); } private function getStopwatch(): Stopwatch { - return $this->getMockBuilder(Stopwatch::class)->getMock(); + return $this->createMock(Stopwatch::class); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php index 0ff5b7915bf5..9c3f2e78d610 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php @@ -12,12 +12,14 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Translation; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerInterface; use Symfony\Bundle\FrameworkBundle\Translation\Translator; use Symfony\Component\Config\Resource\DirectoryResource; use Symfony\Component\Config\Resource\FileExistenceResource; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\Translation\Exception\InvalidArgumentException; use Symfony\Component\Translation\Formatter\MessageFormatter; +use Symfony\Component\Translation\Loader\LoaderInterface; use Symfony\Component\Translation\Loader\YamlFileLoader; use Symfony\Component\Translation\MessageCatalogue; @@ -94,7 +96,7 @@ public function testTransWithCaching() $this->assertEquals('foobarbax (sr@latin)', $translator->trans('foobarbax')); // do it another time as the cache is primed now - $loader = $this->getMockBuilder(\Symfony\Component\Translation\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loader->expects($this->never())->method('load'); $translator = $this->getTranslator($loader, ['cache_dir' => $this->tmpDir]); @@ -124,7 +126,7 @@ public function testTransChoiceWithCaching() $this->assertEquals('other choice 1 (PT-BR)', $translator->transChoice('other choice', 1)); // do it another time as the cache is primed now - $loader = $this->getMockBuilder(\Symfony\Component\Translation\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loader->expects($this->never())->method('load'); $translator = $this->getTranslator($loader, ['cache_dir' => $this->tmpDir]); @@ -139,7 +141,7 @@ public function testTransWithCachingWithInvalidLocale() { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Invalid "invalid locale" locale.'); - $loader = $this->getMockBuilder(\Symfony\Component\Translation\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $translator = $this->getTranslator($loader, ['cache_dir' => $this->tmpDir], 'loader', TranslatorWithInvalidLocale::class); $translator->trans('foo'); @@ -162,7 +164,7 @@ public function testLoadResourcesWithoutCaching() public function testGetDefaultLocale() { - $container = $this->getMockBuilder(ContainerInterface::class)->getMock(); + $container = $this->createMock(\Psr\Container\ContainerInterface::class); $translator = new Translator($container, new MessageFormatter(), 'en'); $this->assertSame('en', $translator->getLocale()); @@ -170,9 +172,9 @@ public function testGetDefaultLocale() public function testInvalidOptions() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The Translator does not support the following options: \'foo\''); - $container = $this->getMockBuilder(\Symfony\Component\DependencyInjection\ContainerInterface::class)->getMock(); + $container = $this->createMock(ContainerInterface::class); (new Translator($container, new MessageFormatter(), 'en', [], ['foo' => 'bar'])); } @@ -182,7 +184,7 @@ public function testResourceFilesOptionLoadsBeforeOtherAddedResources($debug, $e { $someCatalogue = $this->getCatalogue('some_locale', []); - $loader = $this->getMockBuilder(\Symfony\Component\Translation\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loader->expects($this->exactly(2)) ->method('load') @@ -300,7 +302,7 @@ protected function getCatalogue($locale, $messages, $resources = []) protected function getLoader() { - $loader = $this->getMockBuilder(\Symfony\Component\Translation\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loader ->expects($this->exactly(7)) ->method('load') @@ -336,7 +338,7 @@ protected function getLoader() protected function getContainer($loader) { - $container = $this->getMockBuilder(\Symfony\Component\DependencyInjection\ContainerInterface::class)->getMock(); + $container = $this->createMock(ContainerInterface::class); $container ->expects($this->any()) ->method('get') @@ -377,7 +379,7 @@ public function testWarmup() $translator->setFallbackLocales(['fr']); $translator->warmup($this->tmpDir); - $loader = $this->getMockBuilder(\Symfony\Component\Translation\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loader ->expects($this->never()) ->method('load'); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php index 7f697b37ff8e..74bb0404a8e8 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php @@ -220,7 +220,7 @@ public function testGetFirewallReturnsNull() public function testGetListeners() { $request = new Request(); - $event = new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $request, HttpKernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST); $event->setResponse($response = new Response()); $listener = function ($e) use ($event, &$listenerCalled) { $listenerCalled += $e === $event; diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Debug/TraceableFirewallListenerTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/Debug/TraceableFirewallListenerTest.php index b7c6bcc07663..c1be247e812f 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Debug/TraceableFirewallListenerTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Debug/TraceableFirewallListenerTest.php @@ -29,15 +29,12 @@ class TraceableFirewallListenerTest extends TestCase public function testOnKernelRequestRecordsListeners() { $request = new Request(); - $event = new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $request, HttpKernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST); $event->setResponse($response = new Response()); $listener = function ($e) use ($event, &$listenerCalled) { $listenerCalled += $e === $event; }; - $firewallMap = $this - ->getMockBuilder(FirewallMap::class) - ->disableOriginalConstructor() - ->getMock(); + $firewallMap = $this->createMock(FirewallMap::class); $firewallMap ->expects($this->once()) ->method('getFirewallConfig') diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php index bc70434f835f..1ccb9aacaecc 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension; use Symfony\Bundle\SecurityBundle\SecurityBundle; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; @@ -610,7 +611,7 @@ public function testCustomAccessDecisionManagerService() public function testAccessDecisionManagerServiceAndStrategyCannotBeUsedAtTheSameTime() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('Invalid configuration for path "security.access_decision_manager": "strategy" and "service" cannot be used together.'); $this->getContainer('access_decision_manager_service_and_strategy'); } @@ -628,14 +629,14 @@ public function testAccessDecisionManagerOptionsAreNotOverriddenByImplicitStrate public function testFirewallUndefinedUserProvider() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('Invalid firewall "main": user provider "undefined" not found.'); $this->getContainer('firewall_undefined_provider'); } public function testFirewallListenerUndefinedProvider() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('Invalid firewall "main": user provider "undefined" not found.'); $this->getContainer('listener_undefined_provider'); } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/MainConfigurationTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/MainConfigurationTest.php index 86971c38c960..acdfff8d1639 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/MainConfigurationTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/MainConfigurationTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Bundle\SecurityBundle\DependencyInjection\MainConfiguration; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\Config\Definition\Processor; class MainConfigurationTest extends TestCase @@ -34,7 +35,7 @@ class MainConfigurationTest extends TestCase public function testNoConfigForProvider() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $config = [ 'providers' => [ 'stub' => [], @@ -48,7 +49,7 @@ public function testNoConfigForProvider() public function testManyConfigForProvider() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $config = [ 'providers' => [ 'stub' => [ diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/AbstractFactoryTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/AbstractFactoryTest.php index c16539d0c585..c12e0c1e950b 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/AbstractFactoryTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/AbstractFactoryTest.php @@ -12,6 +12,7 @@ namespace Symfony\Bundle\SecurityBundle\Tests\DependencyInjection\Security\Factory; use PHPUnit\Framework\TestCase; +use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AbstractFactory; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; @@ -127,7 +128,7 @@ public function getSuccessHandlers() protected function callFactory($id, $config, $userProviderId, $defaultEntryPointId) { - $factory = $this->getMockForAbstractClass(\Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AbstractFactory::class, []); + $factory = $this->getMockForAbstractClass(AbstractFactory::class); $factory ->expects($this->once()) diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/GuardAuthenticationFactoryTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/GuardAuthenticationFactoryTest.php index a28bed4f5c4c..e5044a2bb92b 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/GuardAuthenticationFactoryTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/GuardAuthenticationFactoryTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\GuardAuthenticationFactory; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; @@ -41,7 +42,7 @@ public function testAddValidConfiguration(array $inputConfig, array $expectedCon */ public function testAddInvalidConfiguration(array $inputConfig) { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $factory = new GuardAuthenticationFactory(); $nodeDefinition = new ArrayNodeDefinition('guard'); $factory->addConfiguration($nodeDefinition); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php index e3d46421902c..48d44bf554f2 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php @@ -16,6 +16,7 @@ use Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension; use Symfony\Bundle\SecurityBundle\SecurityBundle; use Symfony\Bundle\SecurityBundle\Tests\DependencyInjection\Fixtures\UserProvider\DummyProvider; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; @@ -26,7 +27,7 @@ class SecurityExtensionTest extends TestCase { public function testInvalidCheckPath() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('The check_path "/some_area/login_check" for login method "form_login" is not matched by the firewall pattern "/secured_area/.*".'); $container = $this->getRawContainer(); @@ -50,7 +51,7 @@ public function testInvalidCheckPath() public function testFirewallWithoutAuthenticationListener() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('No authentication listener registered for firewall "some_firewall"'); $container = $this->getRawContainer(); @@ -71,7 +72,7 @@ public function testFirewallWithoutAuthenticationListener() public function testFirewallWithInvalidUserProvider() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('Unable to create definition for "security.user.provider.concrete.my_foo" user provider'); $container = $this->getRawContainer(); @@ -190,7 +191,7 @@ public function testPerListenerProvider() public function testMissingProviderForListener() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('Not configuring explicitly the provider for the "http_basic" listener on "ambiguous" firewall is ambiguous as there is more than one registered provider.'); $container = $this->getRawContainer(); $container->loadFromExtension('security', [ diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/UserPasswordEncoderCommandTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/UserPasswordEncoderCommandTest.php index bd94f4d2d619..5846f386b7fc 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/UserPasswordEncoderCommandTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/UserPasswordEncoderCommandTest.php @@ -301,7 +301,7 @@ public function testThrowsExceptionOnNoConfiguredEncoders() $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('There are no configured encoders for the "security" extension.'); $application = new ConsoleApplication(); - $application->add(new UserPasswordEncoderCommand($this->getMockBuilder(EncoderFactoryInterface::class)->getMock(), [])); + $application->add(new UserPasswordEncoderCommand($this->createMock(EncoderFactoryInterface::class), [])); $passwordEncoderCommand = $application->find('security:encode-password'); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallMapTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallMapTest.php index 7e49cd4fde9b..d174e13b5cff 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallMapTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallMapTest.php @@ -30,7 +30,7 @@ public function testGetListenersWithEmptyMap() $request = new Request(); $map = []; - $container = $this->getMockBuilder(Container::class)->getMock(); + $container = $this->createMock(Container::class); $container->expects($this->never())->method('get'); $firewallMap = new FirewallMap($container, $map); @@ -46,7 +46,7 @@ public function testGetListenersWithInvalidParameter() $request->attributes->set(self::ATTRIBUTE_FIREWALL_CONTEXT, 'foo'); $map = []; - $container = $this->getMockBuilder(Container::class)->getMock(); + $container = $this->createMock(Container::class); $container->expects($this->never())->method('get'); $firewallMap = new FirewallMap($container, $map); @@ -60,7 +60,7 @@ public function testGetListeners() { $request = new Request(); - $firewallContext = $this->getMockBuilder(FirewallContext::class)->disableOriginalConstructor()->getMock(); + $firewallContext = $this->createMock(FirewallContext::class); $firewallConfig = new FirewallConfig('main', 'user_checker'); $firewallContext->expects($this->once())->method('getConfig')->willReturn($firewallConfig); @@ -68,19 +68,19 @@ public function testGetListeners() $listener = function () {}; $firewallContext->expects($this->once())->method('getListeners')->willReturn([$listener]); - $exceptionListener = $this->getMockBuilder(ExceptionListener::class)->disableOriginalConstructor()->getMock(); + $exceptionListener = $this->createMock(ExceptionListener::class); $firewallContext->expects($this->once())->method('getExceptionListener')->willReturn($exceptionListener); - $logoutListener = $this->getMockBuilder(LogoutListener::class)->disableOriginalConstructor()->getMock(); + $logoutListener = $this->createMock(LogoutListener::class); $firewallContext->expects($this->once())->method('getLogoutListener')->willReturn($logoutListener); - $matcher = $this->getMockBuilder(RequestMatcherInterface::class)->getMock(); + $matcher = $this->createMock(RequestMatcherInterface::class); $matcher->expects($this->once()) ->method('matches') ->with($request) ->willReturn(true); - $container = $this->getMockBuilder(Container::class)->getMock(); + $container = $this->createMock(Container::class); $container->expects($this->exactly(2))->method('get')->willReturn($firewallContext); $firewallMap = new FirewallMap($container, ['security.firewall.map.context.foo' => $matcher]); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/SecurityUserValueResolverTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/SecurityUserValueResolverTest.php index 177308277d08..8bfda6c2f67c 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/SecurityUserValueResolverTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/SecurityUserValueResolverTest.php @@ -37,8 +37,8 @@ public function testResolveNoToken() public function testResolveNoUser() { - $mock = $this->getMockBuilder(UserInterface::class)->getMock(); - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); + $mock = $this->createMock(UserInterface::class); + $token = $this->createMock(TokenInterface::class); $tokenStorage = new TokenStorage(); $tokenStorage->setToken($token); @@ -59,8 +59,8 @@ public function testResolveWrongType() public function testResolve() { - $user = $this->getMockBuilder(UserInterface::class)->getMock(); - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); + $token = $this->createMock(TokenInterface::class); $token->expects($this->any())->method('getUser')->willReturn($user); $tokenStorage = new TokenStorage(); $tokenStorage->setToken($token); @@ -74,8 +74,8 @@ public function testResolve() public function testIntegration() { - $user = $this->getMockBuilder(UserInterface::class)->getMock(); - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); + $token = $this->createMock(TokenInterface::class); $token->expects($this->any())->method('getUser')->willReturn($user); $tokenStorage = new TokenStorage(); $tokenStorage->setToken($token); @@ -86,7 +86,7 @@ public function testIntegration() public function testIntegrationNoUser() { - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $tokenStorage = new TokenStorage(); $tokenStorage->setToken($token); diff --git a/src/Symfony/Bundle/TwigBundle/Tests/Controller/PreviewErrorControllerTest.php b/src/Symfony/Bundle/TwigBundle/Tests/Controller/PreviewErrorControllerTest.php index e485f43720ad..f6d3cf8a708d 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/Controller/PreviewErrorControllerTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/Controller/PreviewErrorControllerTest.php @@ -30,7 +30,7 @@ public function testForwardRequestToConfiguredController() $code = 123; $logicalControllerName = 'foo:bar:baz'; - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $kernel ->expects($this->once()) ->method('handle') diff --git a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Compiler/TwigLoaderPassTest.php b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Compiler/TwigLoaderPassTest.php index d544dde63cef..68431f969fe1 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Compiler/TwigLoaderPassTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Compiler/TwigLoaderPassTest.php @@ -15,6 +15,7 @@ use Symfony\Bundle\TwigBundle\DependencyInjection\Compiler\TwigLoaderPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Exception\LogicException; class TwigLoaderPassTest extends TestCase { @@ -89,7 +90,7 @@ public function testMapperPassWithTwoTaggedLoadersWithPriority() public function testMapperPassWithZeroTaggedLoaders() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->pass->process($this->builder); } } diff --git a/src/Symfony/Bundle/TwigBundle/Tests/Loader/FilesystemLoaderTest.php b/src/Symfony/Bundle/TwigBundle/Tests/Loader/FilesystemLoaderTest.php index 161032021619..0f43aa847bdc 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/Loader/FilesystemLoaderTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/Loader/FilesystemLoaderTest.php @@ -13,7 +13,10 @@ use Symfony\Bundle\TwigBundle\Loader\FilesystemLoader; use Symfony\Bundle\TwigBundle\Tests\TestCase; +use Symfony\Component\Config\FileLocatorInterface; +use Symfony\Component\Templating\TemplateNameParserInterface; use Symfony\Component\Templating\TemplateReferenceInterface; +use Twig\Error\LoaderError; /** * @group legacy @@ -22,8 +25,8 @@ class FilesystemLoaderTest extends TestCase { public function testGetSourceContext() { - $parser = $this->getMockBuilder(\Symfony\Component\Templating\TemplateNameParserInterface::class)->getMock(); - $locator = $this->getMockBuilder(\Symfony\Component\Config\FileLocatorInterface::class)->getMock(); + $parser = $this->createMock(TemplateNameParserInterface::class); + $locator = $this->createMock(FileLocatorInterface::class); $locator ->expects($this->once()) ->method('locate') @@ -42,8 +45,8 @@ public function testGetSourceContext() public function testExists() { // should return true for templates that Twig does not find, but Symfony does - $parser = $this->getMockBuilder(\Symfony\Component\Templating\TemplateNameParserInterface::class)->getMock(); - $locator = $this->getMockBuilder(\Symfony\Component\Config\FileLocatorInterface::class)->getMock(); + $parser = $this->createMock(TemplateNameParserInterface::class); + $locator = $this->createMock(FileLocatorInterface::class); $locator ->expects($this->once()) ->method('locate') @@ -56,16 +59,16 @@ public function testExists() public function testTwigErrorIfLocatorThrowsInvalid() { - $this->expectException(\Twig\Error\LoaderError::class); - $parser = $this->getMockBuilder(\Symfony\Component\Templating\TemplateNameParserInterface::class)->getMock(); + $this->expectException(LoaderError::class); + $parser = $this->createMock(TemplateNameParserInterface::class); $parser ->expects($this->once()) ->method('parse') ->with('name.format.engine') - ->willReturn($this->getMockBuilder(TemplateReferenceInterface::class)->getMock()) + ->willReturn($this->createMock(TemplateReferenceInterface::class)) ; - $locator = $this->getMockBuilder(\Symfony\Component\Config\FileLocatorInterface::class)->getMock(); + $locator = $this->createMock(FileLocatorInterface::class); $locator ->expects($this->once()) ->method('locate') @@ -78,16 +81,16 @@ public function testTwigErrorIfLocatorThrowsInvalid() public function testTwigErrorIfLocatorReturnsFalse() { - $this->expectException(\Twig\Error\LoaderError::class); - $parser = $this->getMockBuilder(\Symfony\Component\Templating\TemplateNameParserInterface::class)->getMock(); + $this->expectException(LoaderError::class); + $parser = $this->createMock(TemplateNameParserInterface::class); $parser ->expects($this->once()) ->method('parse') ->with('name.format.engine') - ->willReturn($this->getMockBuilder(TemplateReferenceInterface::class)->getMock()) + ->willReturn($this->createMock(TemplateReferenceInterface::class)) ; - $locator = $this->getMockBuilder(\Symfony\Component\Config\FileLocatorInterface::class)->getMock(); + $locator = $this->createMock(FileLocatorInterface::class); $locator ->expects($this->once()) ->method('locate') @@ -100,10 +103,10 @@ public function testTwigErrorIfLocatorReturnsFalse() public function testTwigErrorIfTemplateDoesNotExist() { - $this->expectException(\Twig\Error\LoaderError::class); + $this->expectException(LoaderError::class); $this->expectExceptionMessageMatches('/Unable to find template "name\.format\.engine" \(looked into: .*Tests.Loader.\.\..DependencyInjection.Fixtures.templates\)/'); - $parser = $this->getMockBuilder(\Symfony\Component\Templating\TemplateNameParserInterface::class)->getMock(); - $locator = $this->getMockBuilder(\Symfony\Component\Config\FileLocatorInterface::class)->getMock(); + $parser = $this->createMock(TemplateNameParserInterface::class); + $locator = $this->createMock(FileLocatorInterface::class); $loader = new FilesystemLoader($locator, $parser); $loader->addPath(__DIR__.'/../DependencyInjection/Fixtures/templates'); @@ -115,8 +118,8 @@ public function testTwigErrorIfTemplateDoesNotExist() public function testTwigSoftErrorIfTemplateDoesNotExist() { - $parser = $this->getMockBuilder(\Symfony\Component\Templating\TemplateNameParserInterface::class)->getMock(); - $locator = $this->getMockBuilder(\Symfony\Component\Config\FileLocatorInterface::class)->getMock(); + $parser = $this->createMock(TemplateNameParserInterface::class); + $locator = $this->createMock(FileLocatorInterface::class); $loader = new FilesystemLoader($locator, $parser); $loader->addPath(__DIR__.'/../DependencyInjection/Fixtures/templates'); diff --git a/src/Symfony/Bundle/TwigBundle/Tests/Loader/NativeFilesystemLoaderTest.php b/src/Symfony/Bundle/TwigBundle/Tests/Loader/NativeFilesystemLoaderTest.php index 21b27658023b..ebb5e465129c 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/Loader/NativeFilesystemLoaderTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/Loader/NativeFilesystemLoaderTest.php @@ -4,6 +4,7 @@ use Symfony\Bundle\TwigBundle\Loader\NativeFilesystemLoader; use Symfony\Bundle\TwigBundle\Tests\TestCase; +use Twig\Error\LoaderError; class NativeFilesystemLoaderTest extends TestCase { @@ -17,7 +18,7 @@ public function testWithNativeNamespace() public function testWithLegacyStyle1() { - $this->expectException(\Twig\Error\LoaderError::class); + $this->expectException(LoaderError::class); $this->expectExceptionMessage('Template reference "TestBundle::Foo/index.html.twig" not found, did you mean "@Test/Foo/index.html.twig"?'); $loader = new NativeFilesystemLoader(null, __DIR__.'/../'); $loader->addPath('Fixtures/templates', 'Test'); @@ -27,7 +28,7 @@ public function testWithLegacyStyle1() public function testWithLegacyStyle2() { - $this->expectException(\Twig\Error\LoaderError::class); + $this->expectException(LoaderError::class); $this->expectExceptionMessage('Template reference "TestBundle:Foo:index.html.twig" not found, did you mean "@Test/Foo/index.html.twig"?'); $loader = new NativeFilesystemLoader(null, __DIR__.'/../'); $loader->addPath('Fixtures/templates', 'Test'); diff --git a/src/Symfony/Bundle/TwigBundle/Tests/TemplateIteratorTest.php b/src/Symfony/Bundle/TwigBundle/Tests/TemplateIteratorTest.php index a222e03ecfe4..3c0b9c5b7e38 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/TemplateIteratorTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/TemplateIteratorTest.php @@ -12,16 +12,18 @@ namespace Symfony\Bundle\TwigBundle\Tests; use Symfony\Bundle\TwigBundle\TemplateIterator; +use Symfony\Component\HttpKernel\Bundle\BundleInterface; +use Symfony\Component\HttpKernel\Kernel; class TemplateIteratorTest extends TestCase { public function testGetIterator() { - $bundle = $this->getMockBuilder(\Symfony\Component\HttpKernel\Bundle\BundleInterface::class)->getMock(); + $bundle = $this->createMock(BundleInterface::class); $bundle->expects($this->any())->method('getName')->willReturn('BarBundle'); $bundle->expects($this->any())->method('getPath')->willReturn(__DIR__.'/Fixtures/templates/BarBundle'); - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\Kernel::class)->disableOriginalConstructor()->getMock(); + $kernel = $this->createMock(Kernel::class); $kernel->expects($this->any())->method('getBundles')->willReturn([ $bundle, ]); diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php index 95fff4399771..9115fc795e08 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php @@ -15,6 +15,7 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Bundle\WebProfilerBundle\Controller\ProfilerController; use Symfony\Bundle\WebProfilerBundle\Csp\ContentSecurityPolicyHandler; +use Symfony\Bundle\WebProfilerBundle\Csp\NonceGenerator; use Symfony\Bundle\WebProfilerBundle\Tests\Functional\WebProfilerBundleKernel; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -24,6 +25,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Profiler\Profile; use Symfony\Component\HttpKernel\Profiler\Profiler; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Twig\Environment; use Twig\Loader\LoaderInterface; use Twig\Loader\SourceContextLoaderInterface; @@ -35,8 +37,8 @@ public function testHomeActionWithProfilerDisabled() $this->expectException(NotFoundHttpException::class); $this->expectExceptionMessage('The profiler must be enabled.'); - $urlGenerator = $this->getMockBuilder(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class)->getMock(); - $twig = $this->getMockBuilder(Environment::class)->disableOriginalConstructor()->getMock(); + $urlGenerator = $this->createMock(UrlGeneratorInterface::class); + $twig = $this->createMock(Environment::class); $controller = new ProfilerController($urlGenerator, null, $twig, []); $controller->homeAction(); @@ -111,8 +113,8 @@ public function testToolbarActionWithProfilerDisabled() $this->expectException(NotFoundHttpException::class); $this->expectExceptionMessage('The profiler must be enabled.'); - $urlGenerator = $this->getMockBuilder(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class)->getMock(); - $twig = $this->getMockBuilder(Environment::class)->disableOriginalConstructor()->getMock(); + $urlGenerator = $this->createMock(UrlGeneratorInterface::class); + $twig = $this->createMock(Environment::class); $controller = new ProfilerController($urlGenerator, null, $twig, []); $controller->toolbarAction(Request::create('/_wdt/foo-token'), null); @@ -123,12 +125,9 @@ public function testToolbarActionWithProfilerDisabled() */ public function testToolbarActionWithEmptyToken($token) { - $urlGenerator = $this->getMockBuilder(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class)->getMock(); - $twig = $this->getMockBuilder(Environment::class)->disableOriginalConstructor()->getMock(); - $profiler = $this - ->getMockBuilder(Profiler::class) - ->disableOriginalConstructor() - ->getMock(); + $urlGenerator = $this->createMock(UrlGeneratorInterface::class); + $twig = $this->createMock(Environment::class); + $profiler = $this->createMock(Profiler::class); $controller = new ProfilerController($urlGenerator, $profiler, $twig, []); @@ -150,12 +149,9 @@ public function getEmptyTokenCases() */ public function testOpeningDisallowedPaths($path, $isAllowed) { - $urlGenerator = $this->getMockBuilder(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class)->getMock(); - $twig = $this->getMockBuilder(Environment::class)->disableOriginalConstructor()->getMock(); - $profiler = $this - ->getMockBuilder(Profiler::class) - ->disableOriginalConstructor() - ->getMock(); + $urlGenerator = $this->createMock(UrlGeneratorInterface::class); + $twig = $this->createMock(Environment::class); + $profiler = $this->createMock(Profiler::class); $controller = new ProfilerController($urlGenerator, $profiler, $twig, [], null, __DIR__.'/../..'); @@ -186,11 +182,8 @@ public function getOpenFileCases() */ public function testReturns404onTokenNotFound($withCsp) { - $twig = $this->getMockBuilder(Environment::class)->disableOriginalConstructor()->getMock(); - $profiler = $this - ->getMockBuilder(Profiler::class) - ->disableOriginalConstructor() - ->getMock(); + $twig = $this->createMock(Environment::class); + $profiler = $this->createMock(Profiler::class); $profiler ->expects($this->exactly(2)) @@ -214,8 +207,8 @@ public function testSearchBarActionWithProfilerDisabled() $this->expectException(NotFoundHttpException::class); $this->expectExceptionMessage('The profiler must be enabled.'); - $urlGenerator = $this->getMockBuilder(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class)->getMock(); - $twig = $this->getMockBuilder(Environment::class)->disableOriginalConstructor()->getMock(); + $urlGenerator = $this->createMock(UrlGeneratorInterface::class); + $twig = $this->createMock(Environment::class); $controller = new ProfilerController($urlGenerator, null, $twig, []); $controller->searchBarAction(Request::create('/_profiler/search_bar')); @@ -240,11 +233,8 @@ public function testSearchBarActionDefaultPage() */ public function testSearchResultsAction($withCsp) { - $twig = $this->getMockBuilder(Environment::class)->disableOriginalConstructor()->getMock(); - $profiler = $this - ->getMockBuilder(Profiler::class) - ->disableOriginalConstructor() - ->getMock(); + $twig = $this->createMock(Environment::class); + $profiler = $this->createMock(Profiler::class); $controller = $this->createController($profiler, $twig, $withCsp); @@ -306,8 +296,8 @@ public function testSearchActionWithProfilerDisabled() $this->expectException(NotFoundHttpException::class); $this->expectExceptionMessage('The profiler must be enabled.'); - $urlGenerator = $this->getMockBuilder(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class)->getMock(); - $twig = $this->getMockBuilder(Environment::class)->disableOriginalConstructor()->getMock(); + $urlGenerator = $this->createMock(UrlGeneratorInterface::class); + $twig = $this->createMock(Environment::class); $controller = new ProfilerController($urlGenerator, null, $twig, []); $controller->searchBarAction(Request::create('/_profiler/search')); @@ -345,8 +335,8 @@ public function testPhpinfoActionWithProfilerDisabled() $this->expectException(NotFoundHttpException::class); $this->expectExceptionMessage('The profiler must be enabled.'); - $urlGenerator = $this->getMockBuilder(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class)->getMock(); - $twig = $this->getMockBuilder(Environment::class)->disableOriginalConstructor()->getMock(); + $urlGenerator = $this->createMock(UrlGeneratorInterface::class); + $twig = $this->createMock(Environment::class); $controller = new ProfilerController($urlGenerator, null, $twig, []); $controller->phpinfoAction(Request::create('/_profiler/phpinfo')); @@ -464,10 +454,10 @@ public function defaultPanelProvider(): \Generator private function createController($profiler, $twig, $withCSP, array $templates = []): ProfilerController { - $urlGenerator = $this->getMockBuilder(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class)->getMock(); + $urlGenerator = $this->createMock(UrlGeneratorInterface::class); if ($withCSP) { - $nonceGenerator = $this->getMockBuilder(\Symfony\Bundle\WebProfilerBundle\Csp\NonceGenerator::class)->getMock(); + $nonceGenerator = $this->createMock(NonceGenerator::class); $nonceGenerator->method('generate')->willReturn('dummy_nonce'); return new ProfilerController($urlGenerator, $profiler, $twig, $templates, new ContentSecurityPolicyHandler($nonceGenerator)); diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/Csp/ContentSecurityPolicyHandlerTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/Csp/ContentSecurityPolicyHandlerTest.php index b83ee8a4fdd5..fbaf2f7965d0 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/Csp/ContentSecurityPolicyHandlerTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/Csp/ContentSecurityPolicyHandlerTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Bundle\WebProfilerBundle\Csp\ContentSecurityPolicyHandler; +use Symfony\Bundle\WebProfilerBundle\Csp\NonceGenerator; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -210,7 +211,7 @@ private function createResponse(array $headers = []) private function mockNonceGenerator($value) { - $generator = $this->getMockBuilder(\Symfony\Bundle\WebProfilerBundle\Csp\NonceGenerator::class)->getMock(); + $generator = $this->createMock(NonceGenerator::class); $generator->expects($this->any()) ->method('generate') diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/DependencyInjection/WebProfilerExtensionTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/DependencyInjection/WebProfilerExtensionTest.php index 555d67144ab6..bb666f431602 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/DependencyInjection/WebProfilerExtensionTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/DependencyInjection/WebProfilerExtensionTest.php @@ -52,7 +52,7 @@ protected function setUp(): void { parent::setUp(); - $this->kernel = $this->getMockBuilder(KernelInterface::class)->getMock(); + $this->kernel = $this->createMock(KernelInterface::class); $this->container = new ContainerBuilder(); $this->container->register('error_handler.error_renderer.html', HtmlErrorRenderer::class)->setPublic(true); diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/EventListener/WebDebugToolbarListenerTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/EventListener/WebDebugToolbarListenerTest.php index ed3341be0b5b..30b3edf16463 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/EventListener/WebDebugToolbarListenerTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/EventListener/WebDebugToolbarListenerTest.php @@ -16,9 +16,12 @@ use Symfony\Component\HttpFoundation\HeaderBag; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpKernel\Event\ResponseEvent; use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use Twig\Environment; class WebDebugToolbarListenerTest extends TestCase { @@ -310,7 +313,7 @@ protected function getRequestMock($isXmlHttpRequest = false, $requestFormat = 'h $request->headers = new HeaderBag(); if ($hasSession) { - $session = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\Session::class)->disableOriginalConstructor()->getMock(); + $session = $this->createMock(Session::class); $request->expects($this->any()) ->method('getSession') ->willReturn($session); @@ -321,7 +324,7 @@ protected function getRequestMock($isXmlHttpRequest = false, $requestFormat = 'h protected function getTwigMock($render = 'WDT') { - $templating = $this->getMockBuilder(\Twig\Environment::class)->disableOriginalConstructor()->getMock(); + $templating = $this->createMock(Environment::class); $templating->expects($this->any()) ->method('render') ->willReturn($render); @@ -331,11 +334,11 @@ protected function getTwigMock($render = 'WDT') protected function getUrlGeneratorMock() { - return $this->getMockBuilder(UrlGeneratorInterface::class)->getMock(); + return $this->createMock(UrlGeneratorInterface::class); } protected function getKernelMock() { - return $this->getMockBuilder(\Symfony\Component\HttpKernel\Kernel::class)->disableOriginalConstructor()->getMock(); + return $this->createMock(Kernel::class); } } diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php index 66895312d745..9b43ab535073 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php @@ -13,7 +13,9 @@ use Symfony\Bundle\WebProfilerBundle\Profiler\TemplateManager; use Symfony\Bundle\WebProfilerBundle\Tests\TestCase; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Profiler\Profile; +use Symfony\Component\HttpKernel\Profiler\Profiler; use Twig\Environment; use Twig\Loader\LoaderInterface; use Twig\Loader\SourceContextLoaderInterface; @@ -31,7 +33,7 @@ class TemplateManagerTest extends TestCase protected $twigEnvironment; /** - * @var \Symfony\Component\HttpKernel\Profiler\Profiler + * @var Profiler */ protected $profiler; @@ -57,7 +59,7 @@ protected function setUp(): void public function testGetNameOfInvalidTemplate() { - $this->expectException(\Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class); + $this->expectException(NotFoundHttpException::class); $this->templateManager->getName(new Profile('token'), 'notexistingpanel'); } @@ -98,12 +100,12 @@ public function profileHasCollectorCallback($panel) protected function mockProfile() { - return $this->getMockBuilder(Profile::class)->disableOriginalConstructor()->getMock(); + return $this->createMock(Profile::class); } protected function mockTwigEnvironment() { - $this->twigEnvironment = $this->getMockBuilder(Environment::class)->disableOriginalConstructor()->getMock(); + $this->twigEnvironment = $this->createMock(Environment::class); if (Environment::MAJOR_VERSION > 1) { $loader = $this->createMock(LoaderInterface::class); @@ -122,9 +124,7 @@ protected function mockTwigEnvironment() protected function mockProfiler() { - $this->profiler = $this->getMockBuilder(\Symfony\Component\HttpKernel\Profiler\Profiler::class) - ->disableOriginalConstructor() - ->getMock(); + $this->profiler = $this->createMock(Profiler::class); return $this->profiler; } diff --git a/src/Symfony/Component/Asset/Tests/Context/RequestStackContextTest.php b/src/Symfony/Component/Asset/Tests/Context/RequestStackContextTest.php index accc39ccdde9..ed323749af04 100644 --- a/src/Symfony/Component/Asset/Tests/Context/RequestStackContextTest.php +++ b/src/Symfony/Component/Asset/Tests/Context/RequestStackContextTest.php @@ -13,12 +13,14 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Asset\Context\RequestStackContext; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; class RequestStackContextTest extends TestCase { public function testGetBasePathEmpty() { - $requestStack = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestStack::class)->getMock(); + $requestStack = $this->createMock(RequestStack::class); $requestStackContext = new RequestStackContext($requestStack); $this->assertEmpty($requestStackContext->getBasePath()); @@ -28,10 +30,10 @@ public function testGetBasePathSet() { $testBasePath = 'test-path'; - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->getMock(); + $request = $this->createMock(Request::class); $request->method('getBasePath') ->willReturn($testBasePath); - $requestStack = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestStack::class)->getMock(); + $requestStack = $this->createMock(RequestStack::class); $requestStack->method('getMasterRequest') ->willReturn($request); @@ -42,7 +44,7 @@ public function testGetBasePathSet() public function testIsSecureFalse() { - $requestStack = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestStack::class)->getMock(); + $requestStack = $this->createMock(RequestStack::class); $requestStackContext = new RequestStackContext($requestStack); $this->assertFalse($requestStackContext->isSecure()); @@ -50,10 +52,10 @@ public function testIsSecureFalse() public function testIsSecureTrue() { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->getMock(); + $request = $this->createMock(Request::class); $request->method('isSecure') ->willReturn(true); - $requestStack = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestStack::class)->getMock(); + $requestStack = $this->createMock(RequestStack::class); $requestStack->method('getMasterRequest') ->willReturn($request); @@ -64,7 +66,7 @@ public function testIsSecureTrue() public function testDefaultContext() { - $requestStack = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestStack::class)->getMock(); + $requestStack = $this->createMock(RequestStack::class); $requestStackContext = new RequestStackContext($requestStack, 'default-path', true); $this->assertSame('default-path', $requestStackContext->getBasePath()); diff --git a/src/Symfony/Component/Asset/Tests/PackagesTest.php b/src/Symfony/Component/Asset/Tests/PackagesTest.php index fd16697f5a48..38044a93654e 100644 --- a/src/Symfony/Component/Asset/Tests/PackagesTest.php +++ b/src/Symfony/Component/Asset/Tests/PackagesTest.php @@ -12,7 +12,10 @@ namespace Symfony\Component\Asset\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Asset\Exception\InvalidArgumentException; +use Symfony\Component\Asset\Exception\LogicException; use Symfony\Component\Asset\Package; +use Symfony\Component\Asset\PackageInterface; use Symfony\Component\Asset\Packages; use Symfony\Component\Asset\VersionStrategy\StaticVersionStrategy; @@ -21,8 +24,8 @@ class PackagesTest extends TestCase public function testGetterSetters() { $packages = new Packages(); - $packages->setDefaultPackage($default = $this->getMockBuilder(\Symfony\Component\Asset\PackageInterface::class)->getMock()); - $packages->addPackage('a', $a = $this->getMockBuilder(\Symfony\Component\Asset\PackageInterface::class)->getMock()); + $packages->setDefaultPackage($default = $this->createMock(PackageInterface::class)); + $packages->addPackage('a', $a = $this->createMock(PackageInterface::class)); $this->assertSame($default, $packages->getPackage()); $this->assertSame($a, $packages->getPackage('a')); @@ -57,14 +60,14 @@ public function testGetUrl() public function testNoDefaultPackage() { - $this->expectException(\Symfony\Component\Asset\Exception\LogicException::class); + $this->expectException(LogicException::class); $packages = new Packages(); $packages->getPackage(); } public function testUndefinedPackage() { - $this->expectException(\Symfony\Component\Asset\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $packages = new Packages(); $packages->getPackage('a'); } diff --git a/src/Symfony/Component/Asset/Tests/PathPackageTest.php b/src/Symfony/Component/Asset/Tests/PathPackageTest.php index c006369bcbda..57bb80bcccf0 100644 --- a/src/Symfony/Component/Asset/Tests/PathPackageTest.php +++ b/src/Symfony/Component/Asset/Tests/PathPackageTest.php @@ -12,8 +12,10 @@ namespace Symfony\Component\Asset\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Asset\Context\ContextInterface; use Symfony\Component\Asset\PathPackage; use Symfony\Component\Asset\VersionStrategy\StaticVersionStrategy; +use Symfony\Component\Asset\VersionStrategy\VersionStrategyInterface; class PathPackageTest extends TestCase { @@ -77,7 +79,7 @@ public function getContextConfigs() public function testVersionStrategyGivesAbsoluteURL() { - $versionStrategy = $this->getMockBuilder(\Symfony\Component\Asset\VersionStrategy\VersionStrategyInterface::class)->getMock(); + $versionStrategy = $this->createMock(VersionStrategyInterface::class); $versionStrategy->expects($this->any()) ->method('applyVersion') ->willReturn('https://cdn.com/bar/main.css'); @@ -88,7 +90,7 @@ public function testVersionStrategyGivesAbsoluteURL() private function getContext($basePath) { - $context = $this->getMockBuilder(\Symfony\Component\Asset\Context\ContextInterface::class)->getMock(); + $context = $this->createMock(ContextInterface::class); $context->expects($this->any())->method('getBasePath')->willReturn($basePath); return $context; diff --git a/src/Symfony/Component/Asset/Tests/UrlPackageTest.php b/src/Symfony/Component/Asset/Tests/UrlPackageTest.php index 690eb3840674..717c0687c987 100644 --- a/src/Symfony/Component/Asset/Tests/UrlPackageTest.php +++ b/src/Symfony/Component/Asset/Tests/UrlPackageTest.php @@ -12,9 +12,13 @@ namespace Symfony\Component\Asset\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Asset\Context\ContextInterface; +use Symfony\Component\Asset\Exception\InvalidArgumentException; +use Symfony\Component\Asset\Exception\LogicException; use Symfony\Component\Asset\UrlPackage; use Symfony\Component\Asset\VersionStrategy\EmptyVersionStrategy; use Symfony\Component\Asset\VersionStrategy\StaticVersionStrategy; +use Symfony\Component\Asset\VersionStrategy\VersionStrategyInterface; class UrlPackageTest extends TestCase { @@ -86,7 +90,7 @@ public function getContextConfigs() public function testVersionStrategyGivesAbsoluteURL() { - $versionStrategy = $this->getMockBuilder(\Symfony\Component\Asset\VersionStrategy\VersionStrategyInterface::class)->getMock(); + $versionStrategy = $this->createMock(VersionStrategyInterface::class); $versionStrategy->expects($this->any()) ->method('applyVersion') ->willReturn('https://cdn.com/bar/main.css'); @@ -97,7 +101,7 @@ public function testVersionStrategyGivesAbsoluteURL() public function testNoBaseUrls() { - $this->expectException(\Symfony\Component\Asset\Exception\LogicException::class); + $this->expectException(LogicException::class); new UrlPackage([], new EmptyVersionStrategy()); } @@ -106,7 +110,7 @@ public function testNoBaseUrls() */ public function testWrongBaseUrl($baseUrls) { - $this->expectException(\Symfony\Component\Asset\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); new UrlPackage($baseUrls, new EmptyVersionStrategy()); } @@ -120,7 +124,7 @@ public function getWrongBaseUrlConfig() private function getContext($secure) { - $context = $this->getMockBuilder(\Symfony\Component\Asset\Context\ContextInterface::class)->getMock(); + $context = $this->createMock(ContextInterface::class); $context->expects($this->any())->method('isSecure')->willReturn($secure); return $context; diff --git a/src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php b/src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php index 716ad88009dd..1e4b51fa5372 100644 --- a/src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php +++ b/src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php @@ -15,6 +15,7 @@ use Symfony\Component\BrowserKit\Client; use Symfony\Component\BrowserKit\CookieJar; use Symfony\Component\BrowserKit\History; +use Symfony\Component\BrowserKit\Request; use Symfony\Component\BrowserKit\Response; class AbstractBrowserTest extends TestCase @@ -841,7 +842,7 @@ public function testInternalRequest() 'NEW_SERVER_KEY' => 'new-server-key-value', ]); - $this->assertInstanceOf(\Symfony\Component\BrowserKit\Request::class, $client->getInternalRequest()); + $this->assertInstanceOf(Request::class, $client->getInternalRequest()); } /** diff --git a/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php index c381854b23bc..0734e9818cc4 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php @@ -17,6 +17,7 @@ use Symfony\Component\Cache\Adapter\ChainAdapter; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Component\Cache\CacheItem; +use Symfony\Component\Cache\Exception\InvalidArgumentException; use Symfony\Component\Cache\Tests\Fixtures\ExternalAdapter; use Symfony\Component\Cache\Tests\Fixtures\PrunableAdapter; use Symfony\Component\Filesystem\Filesystem; @@ -44,14 +45,14 @@ public static function tearDownAfterClass(): void public function testEmptyAdaptersException() { - $this->expectException(\Symfony\Component\Cache\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('At least one adapter must be specified.'); new ChainAdapter([]); } public function testInvalidAdapterException() { - $this->expectException(\Symfony\Component\Cache\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The class "stdClass" does not implement'); new ChainAdapter([new \stdClass()]); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/MaxIdLengthAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/MaxIdLengthAdapterTest.php index 897032704915..7120558f0f36 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/MaxIdLengthAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/MaxIdLengthAdapterTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Cache\Adapter\AbstractAdapter; +use Symfony\Component\Cache\Exception\InvalidArgumentException; class MaxIdLengthAdapterTest extends TestCase { @@ -68,7 +69,7 @@ public function testLongKeyVersioning() public function testTooLongNamespace() { - $this->expectException(\Symfony\Component\Cache\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Namespace must be 26 chars max, 40 given ("----------------------------------------")'); $this->getMockBuilder(MaxIdLengthAdapter::class) ->setConstructorArgs([str_repeat('-', 40)]) diff --git a/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php index 25fef079850d..0a67ea18467c 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php @@ -14,6 +14,7 @@ use Psr\Cache\CacheItemPoolInterface; use Symfony\Component\Cache\Adapter\AbstractAdapter; use Symfony\Component\Cache\Adapter\MemcachedAdapter; +use Symfony\Component\Cache\Exception\CacheException; /** * @group integration @@ -106,7 +107,7 @@ public function testDefaultOptions() public function testOptionSerializer() { - $this->expectException(\Symfony\Component\Cache\Exception\CacheException::class); + $this->expectException(CacheException::class); $this->expectExceptionMessage('MemcachedAdapter: "serializer" option must be "php" or "igbinary".'); if (!\Memcached::HAVE_JSON) { $this->markTestSkipped('Memcached::HAVE_JSON required'); diff --git a/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterSentinelTest.php b/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterSentinelTest.php index 3c250a5e6fe6..0eb407bafa5b 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterSentinelTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterSentinelTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Cache\Adapter\AbstractAdapter; use Symfony\Component\Cache\Adapter\RedisAdapter; +use Symfony\Component\Cache\Exception\InvalidArgumentException; /** * @group integration @@ -36,7 +37,7 @@ public static function setUpBeforeClass(): void public function testInvalidDSNHasBothClusterAndSentinel() { - $this->expectException(\Symfony\Component\Cache\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Cannot use both "redis_cluster" and "redis_sentinel" at the same time:'); $dsn = 'redis:?host[redis1]&host[redis2]&host[redis3]&redis_cluster=1&redis_sentinel=mymaster'; RedisAdapter::createConnection($dsn); diff --git a/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterTest.php index 0e4f93037707..514a0e92e1ba 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterTest.php @@ -14,6 +14,7 @@ use Psr\Cache\CacheItemPoolInterface; use Symfony\Component\Cache\Adapter\AbstractAdapter; use Symfony\Component\Cache\Adapter\RedisAdapter; +use Symfony\Component\Cache\Exception\InvalidArgumentException; use Symfony\Component\Cache\Traits\RedisProxy; /** @@ -70,7 +71,7 @@ public function testCreateConnection(string $dsnScheme) */ public function testFailedCreateConnection(string $dsn) { - $this->expectException(\Symfony\Component\Cache\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Redis connection '); RedisAdapter::createConnection($dsn); } @@ -89,7 +90,7 @@ public function provideFailedCreateConnection(): array */ public function testInvalidCreateConnection(string $dsn) { - $this->expectException(\Symfony\Component\Cache\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid Redis DSN'); RedisAdapter::createConnection($dsn); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/RedisClusterAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/RedisClusterAdapterTest.php index 92a96784614a..1253aeb5007a 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/RedisClusterAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/RedisClusterAdapterTest.php @@ -14,6 +14,7 @@ use Psr\Cache\CacheItemPoolInterface; use Symfony\Component\Cache\Adapter\AbstractAdapter; use Symfony\Component\Cache\Adapter\RedisAdapter; +use Symfony\Component\Cache\Exception\InvalidArgumentException; use Symfony\Component\Cache\Traits\RedisClusterProxy; /** @@ -46,7 +47,7 @@ public function createCachePool(int $defaultLifetime = 0): CacheItemPoolInterfac */ public function testFailedCreateConnection(string $dsn) { - $this->expectException(\Symfony\Component\Cache\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Redis connection '); RedisAdapter::createConnection($dsn); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php index 4d60f4cbd418..ba2636cfe2fd 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php @@ -72,9 +72,7 @@ public function testPrune() public function testKnownTagVersionsTtl() { $itemsPool = new FilesystemAdapter('', 10); - $tagsPool = $this - ->getMockBuilder(AdapterInterface::class) - ->getMock(); + $tagsPool = $this->createMock(AdapterInterface::class); $pool = new TagAwareAdapter($itemsPool, $tagsPool, 10); @@ -82,7 +80,7 @@ public function testKnownTagVersionsTtl() $item->tag(['baz']); $item->expiresAfter(100); - $tag = $this->getMockBuilder(CacheItemInterface::class)->getMock(); + $tag = $this->createMock(CacheItemInterface::class); $tag->expects(self::exactly(2))->method('get')->willReturn(10); $tagsPool->expects(self::exactly(2))->method('getItems')->willReturn([ diff --git a/src/Symfony/Component/Cache/Tests/CacheItemTest.php b/src/Symfony/Component/Cache/Tests/CacheItemTest.php index d667aa126193..bf9afc56c270 100644 --- a/src/Symfony/Component/Cache/Tests/CacheItemTest.php +++ b/src/Symfony/Component/Cache/Tests/CacheItemTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Cache\CacheItem; +use Symfony\Component\Cache\Exception\InvalidArgumentException; +use Symfony\Component\Cache\Exception\LogicException; use Symfony\Component\Cache\Tests\Fixtures\StringableTag; class CacheItemTest extends TestCase @@ -27,7 +29,7 @@ public function testValidKey() */ public function testInvalidKey($key) { - $this->expectException(\Symfony\Component\Cache\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Cache key'); CacheItem::validateKey($key); } @@ -75,7 +77,7 @@ public function testTag() */ public function testInvalidTag($tag) { - $this->expectException(\Symfony\Component\Cache\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Cache tag'); $item = new CacheItem(); $r = new \ReflectionProperty($item, 'isTaggable'); @@ -87,7 +89,7 @@ public function testInvalidTag($tag) public function testNonTaggableItem() { - $this->expectException(\Symfony\Component\Cache\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Cache item "foo" comes from a non tag-aware pool: you cannot tag it.'); $item = new CacheItem(); $r = new \ReflectionProperty($item, 'key'); diff --git a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php index 7225d630e115..8329cd2bd7fc 100644 --- a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php +++ b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php @@ -17,6 +17,7 @@ use Symfony\Component\Cache\DependencyInjection\CachePoolPrunerPass; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Reference; class CachePoolPrunerPassTest extends TestCase @@ -58,7 +59,7 @@ public function testCompilePassIsIgnoredIfCommandDoesNotExist() public function testCompilerPassThrowsOnInvalidDefinitionClass() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Class "Symfony\Component\Cache\Tests\DependencyInjection\NotFound" used for service "pool.not-found" cannot be found.'); $container = new ContainerBuilder(); $container->register('console.command.cache_pool_prune')->addArgument([]); diff --git a/src/Symfony/Component/Cache/Tests/Simple/ChainCacheTest.php b/src/Symfony/Component/Cache/Tests/Simple/ChainCacheTest.php index c65cf92c6a97..c38164bdc7d8 100644 --- a/src/Symfony/Component/Cache/Tests/Simple/ChainCacheTest.php +++ b/src/Symfony/Component/Cache/Tests/Simple/ChainCacheTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Cache\Tests\Simple; use Psr\SimpleCache\CacheInterface; +use Symfony\Component\Cache\Exception\InvalidArgumentException; use Symfony\Component\Cache\Simple\ArrayCache; use Symfony\Component\Cache\Simple\ChainCache; use Symfony\Component\Cache\Simple\FilesystemCache; @@ -30,14 +31,14 @@ public function createSimpleCache(int $defaultLifetime = 0): CacheInterface public function testEmptyCachesException() { - $this->expectException(\Symfony\Component\Cache\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('At least one cache must be specified.'); new ChainCache([]); } public function testInvalidCacheException() { - $this->expectException(\Symfony\Component\Cache\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The class "stdClass" does not implement'); new ChainCache([new \stdClass()]); } diff --git a/src/Symfony/Component/Cache/Tests/Simple/MemcachedCacheTest.php b/src/Symfony/Component/Cache/Tests/Simple/MemcachedCacheTest.php index 707c20508971..a76eeaafa1db 100644 --- a/src/Symfony/Component/Cache/Tests/Simple/MemcachedCacheTest.php +++ b/src/Symfony/Component/Cache/Tests/Simple/MemcachedCacheTest.php @@ -13,6 +13,7 @@ use Psr\SimpleCache\CacheInterface; use Symfony\Component\Cache\Adapter\AbstractAdapter; +use Symfony\Component\Cache\Exception\CacheException; use Symfony\Component\Cache\Simple\MemcachedCache; /** @@ -115,7 +116,7 @@ public function testDefaultOptions() public function testOptionSerializer() { - $this->expectException(\Symfony\Component\Cache\Exception\CacheException::class); + $this->expectException(CacheException::class); $this->expectExceptionMessage('MemcachedAdapter: "serializer" option must be "php" or "igbinary".'); if (!\Memcached::HAVE_JSON) { $this->markTestSkipped('Memcached::HAVE_JSON required'); diff --git a/src/Symfony/Component/Cache/Tests/Simple/RedisCacheTest.php b/src/Symfony/Component/Cache/Tests/Simple/RedisCacheTest.php index 770d8ff9e9bf..5e3361c97bb5 100644 --- a/src/Symfony/Component/Cache/Tests/Simple/RedisCacheTest.php +++ b/src/Symfony/Component/Cache/Tests/Simple/RedisCacheTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Cache\Tests\Simple; +use Symfony\Component\Cache\Exception\InvalidArgumentException; use Symfony\Component\Cache\Simple\RedisCache; /** @@ -52,7 +53,7 @@ public function testCreateConnection() */ public function testFailedCreateConnection(string $dsn) { - $this->expectException(\Symfony\Component\Cache\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Redis connection '); RedisCache::createConnection($dsn); } @@ -71,7 +72,7 @@ public function provideFailedCreateConnection(): array */ public function testInvalidCreateConnection(string $dsn) { - $this->expectException(\Symfony\Component\Cache\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid Redis DSN'); RedisCache::createConnection($dsn); } diff --git a/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php index 1f4d09835a41..54a966f1779f 100644 --- a/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php @@ -14,13 +14,14 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\ArrayNode; use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; +use Symfony\Component\Config\Definition\Exception\InvalidTypeException; use Symfony\Component\Config\Definition\ScalarNode; class ArrayNodeTest extends TestCase { public function testNormalizeThrowsExceptionWhenFalseIsNotAllowed() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidTypeException::class); + $this->expectException(InvalidTypeException::class); $node = new ArrayNode('root'); $node->normalize(false); } diff --git a/src/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.php index 929b69755f94..3a05e3efd815 100644 --- a/src/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\BooleanNode; +use Symfony\Component\Config\Definition\Exception\InvalidTypeException; class BooleanNodeTest extends TestCase { @@ -51,7 +52,7 @@ public function getValidValues() */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidTypeException::class); + $this->expectException(InvalidTypeException::class); $node = new BooleanNode('test'); $node->normalize($value); } diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php index 765c94a6ba4e..0e489ac91097 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php @@ -16,8 +16,10 @@ use Symfony\Component\Config\Definition\Builder\BooleanNodeDefinition; use Symfony\Component\Config\Definition\Builder\NodeDefinition; use Symfony\Component\Config\Definition\Builder\ScalarNodeDefinition; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException; use Symfony\Component\Config\Definition\Processor; +use Symfony\Component\Config\Definition\PrototypedArrayNode; class ArrayNodeDefinitionTest extends TestCase { @@ -152,8 +154,8 @@ public function testNestedPrototypedArrayNodes() ; $node = $nodeDefinition->getNode(); - $this->assertInstanceOf(\Symfony\Component\Config\Definition\PrototypedArrayNode::class, $node); - $this->assertInstanceOf(\Symfony\Component\Config\Definition\PrototypedArrayNode::class, $node->getPrototype()); + $this->assertInstanceOf(PrototypedArrayNode::class, $node); + $this->assertInstanceOf(PrototypedArrayNode::class, $node->getPrototype()); } public function testEnabledNodeDefaults() @@ -317,7 +319,7 @@ public function testRequiresAtLeastOneElement() public function testCannotBeEmpty() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('The path "root" should have at least 1 element(s) defined.'); $node = new ArrayNodeDefinition('root'); $node diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php index bca66a0a59d5..79ec5a357c0b 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php @@ -13,12 +13,13 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\Builder\BooleanNodeDefinition; +use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException; class BooleanNodeDefinitionTest extends TestCase { public function testCannotBeEmptyThrowsAnException() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidDefinitionException::class); + $this->expectException(InvalidDefinitionException::class); $this->expectExceptionMessage('->cannotBeEmpty() is not applicable to BooleanNodeDefinition.'); $def = new BooleanNodeDefinition('foo'); $def->cannotBeEmpty(); diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/ExprBuilderTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/ExprBuilderTest.php index e2b14751b1cb..c634f0887714 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/ExprBuilderTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/ExprBuilderTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\Builder\ExprBuilder; use Symfony\Component\Config\Definition\Builder\TreeBuilder; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; class ExprBuilderTest extends TestCase { @@ -167,7 +168,7 @@ public function castToArrayValues() public function testThenInvalid() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $test = $this->getTestBuilder() ->ifString() ->thenInvalid('Invalid value') diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/NodeBuilderTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/NodeBuilderTest.php index e29a09105300..b272008fedf2 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/NodeBuilderTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/NodeBuilderTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\Config\Tests\Definition\Builder; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Definition\Builder\FloatNodeDefinition; +use Symfony\Component\Config\Definition\Builder\IntegerNodeDefinition; use Symfony\Component\Config\Definition\Builder\NodeBuilder as BaseNodeBuilder; use Symfony\Component\Config\Definition\Builder\VariableNodeDefinition as BaseVariableNodeDefinition; @@ -79,10 +81,10 @@ public function testNumericNodeCreation() $builder = new BaseNodeBuilder(); $node = $builder->integerNode('foo')->min(3)->max(5); - $this->assertInstanceOf(\Symfony\Component\Config\Definition\Builder\IntegerNodeDefinition::class, $node); + $this->assertInstanceOf(IntegerNodeDefinition::class, $node); $node = $builder->floatNode('bar')->min(3.0)->max(5.0); - $this->assertInstanceOf(\Symfony\Component\Config\Definition\Builder\FloatNodeDefinition::class, $node); + $this->assertInstanceOf(FloatNodeDefinition::class, $node); } } diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.php index b0a3983756f2..06ce62e80916 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.php @@ -14,6 +14,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\Builder\FloatNodeDefinition; use Symfony\Component\Config\Definition\Builder\IntegerNodeDefinition; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; +use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException; class NumericNodeDefinitionTest extends TestCase { @@ -35,7 +37,7 @@ public function testIncoherentMaxAssertion() public function testIntegerMinAssertion() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('The value 4 is too small for path "foo". Should be greater than or equal to 5'); $def = new IntegerNodeDefinition('foo'); $def->min(5)->getNode()->finalize(4); @@ -43,7 +45,7 @@ public function testIntegerMinAssertion() public function testIntegerMaxAssertion() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('The value 4 is too big for path "foo". Should be less than or equal to 3'); $def = new IntegerNodeDefinition('foo'); $def->max(3)->getNode()->finalize(4); @@ -58,7 +60,7 @@ public function testIntegerValidMinMaxAssertion() public function testFloatMinAssertion() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('The value 400 is too small for path "foo". Should be greater than or equal to 500'); $def = new FloatNodeDefinition('foo'); $def->min(5E2)->getNode()->finalize(4e2); @@ -66,7 +68,7 @@ public function testFloatMinAssertion() public function testFloatMaxAssertion() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('The value 4.3 is too big for path "foo". Should be less than or equal to 0.3'); $def = new FloatNodeDefinition('foo'); $def->max(0.3)->getNode()->finalize(4.3); @@ -81,7 +83,7 @@ public function testFloatValidMinMaxAssertion() public function testCannotBeEmptyThrowsAnException() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidDefinitionException::class); + $this->expectException(InvalidDefinitionException::class); $this->expectExceptionMessage('->cannotBeEmpty() is not applicable to NumericNodeDefinition.'); $def = new IntegerNodeDefinition('foo'); $def->cannotBeEmpty(); diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/TreeBuilderTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/TreeBuilderTest.php index 96b1b4c2dea7..8f5e79d36fef 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/TreeBuilderTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/TreeBuilderTest.php @@ -12,8 +12,14 @@ namespace Symfony\Component\Config\Tests\Definition\Builder; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Definition\BaseNode; +use Symfony\Component\Config\Definition\BooleanNode; +use Symfony\Component\Config\Definition\Builder\BooleanNodeDefinition; use Symfony\Component\Config\Definition\Builder\TreeBuilder; +use Symfony\Component\Config\Tests\Fixtures\BarNode; +use Symfony\Component\Config\Tests\Fixtures\Builder\BarNodeDefinition; use Symfony\Component\Config\Tests\Fixtures\Builder\NodeBuilder as CustomNodeBuilder; +use Symfony\Component\Config\Tests\Fixtures\Builder\VariableNodeDefinition; class TreeBuilderTest extends TestCase { @@ -23,11 +29,11 @@ public function testUsingACustomNodeBuilder() $nodeBuilder = $builder->getRootNode()->children(); - $this->assertInstanceOf(\Symfony\Component\Config\Tests\Fixtures\Builder\NodeBuilder::class, $nodeBuilder); + $this->assertInstanceOf(CustomNodeBuilder::class, $nodeBuilder); $nodeBuilder = $nodeBuilder->arrayNode('deeper')->children(); - $this->assertInstanceOf(\Symfony\Component\Config\Tests\Fixtures\Builder\NodeBuilder::class, $nodeBuilder); + $this->assertInstanceOf(CustomNodeBuilder::class, $nodeBuilder); } public function testOverrideABuiltInNodeType() @@ -36,7 +42,7 @@ public function testOverrideABuiltInNodeType() $definition = $builder->getRootNode()->children()->variableNode('variable'); - $this->assertInstanceOf(\Symfony\Component\Config\Tests\Fixtures\Builder\VariableNodeDefinition::class, $definition); + $this->assertInstanceOf(VariableNodeDefinition::class, $definition); } public function testAddANodeType() @@ -45,7 +51,7 @@ public function testAddANodeType() $definition = $builder->getRootNode()->children()->barNode('variable'); - $this->assertInstanceOf(\Symfony\Component\Config\Tests\Fixtures\Builder\BarNodeDefinition::class, $definition); + $this->assertInstanceOf(BarNodeDefinition::class, $definition); } public function testCreateABuiltInNodeTypeWithACustomNodeBuilder() @@ -54,7 +60,7 @@ public function testCreateABuiltInNodeTypeWithACustomNodeBuilder() $definition = $builder->getRootNode()->children()->booleanNode('boolean'); - $this->assertInstanceOf(\Symfony\Component\Config\Definition\Builder\BooleanNodeDefinition::class, $definition); + $this->assertInstanceOf(BooleanNodeDefinition::class, $definition); } public function testPrototypedArrayNodeUseTheCustomNodeBuilder() @@ -64,7 +70,7 @@ public function testPrototypedArrayNodeUseTheCustomNodeBuilder() $root = $builder->getRootNode(); $root->prototype('bar')->end(); - $this->assertInstanceOf(\Symfony\Component\Config\Tests\Fixtures\BarNode::class, $root->getNode(true)->getPrototype()); + $this->assertInstanceOf(BarNode::class, $root->getNode(true)->getPrototype()); } public function testAnExtendedNodeBuilderGetsPropagatedToTheChildren() @@ -86,11 +92,11 @@ public function testAnExtendedNodeBuilderGetsPropagatedToTheChildren() $node = $builder->buildTree(); $children = $node->getChildren(); - $this->assertInstanceOf(\Symfony\Component\Config\Definition\BooleanNode::class, $children['foo']); + $this->assertInstanceOf(BooleanNode::class, $children['foo']); $childChildren = $children['child']->getChildren(); - $this->assertInstanceOf(\Symfony\Component\Config\Definition\BooleanNode::class, $childChildren['foo']); + $this->assertInstanceOf(BooleanNode::class, $childChildren['foo']); } public function testDefinitionInfoGetsTransferredToNode() @@ -147,14 +153,14 @@ public function testDefaultPathSeparatorIsDot() $children = $node->getChildren(); $this->assertArrayHasKey('foo', $children); - $this->assertInstanceOf(\Symfony\Component\Config\Definition\BaseNode::class, $children['foo']); + $this->assertInstanceOf(BaseNode::class, $children['foo']); $this->assertSame('propagation.foo', $children['foo']->getPath()); $this->assertArrayHasKey('child', $children); $childChildren = $children['child']->getChildren(); $this->assertArrayHasKey('foo', $childChildren); - $this->assertInstanceOf(\Symfony\Component\Config\Definition\BaseNode::class, $childChildren['foo']); + $this->assertInstanceOf(BaseNode::class, $childChildren['foo']); $this->assertSame('propagation.child.foo', $childChildren['foo']->getPath()); } @@ -178,14 +184,14 @@ public function testPathSeparatorIsPropagatedToChildren() $children = $node->getChildren(); $this->assertArrayHasKey('foo', $children); - $this->assertInstanceOf(\Symfony\Component\Config\Definition\BaseNode::class, $children['foo']); + $this->assertInstanceOf(BaseNode::class, $children['foo']); $this->assertSame('propagation/foo', $children['foo']->getPath()); $this->assertArrayHasKey('child', $children); $childChildren = $children['child']->getChildren(); $this->assertArrayHasKey('foo', $childChildren); - $this->assertInstanceOf(\Symfony\Component\Config\Definition\BaseNode::class, $childChildren['foo']); + $this->assertInstanceOf(BaseNode::class, $childChildren['foo']); $this->assertSame('propagation/child/foo', $childChildren['foo']->getPath()); } diff --git a/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php index 1d5136ce5b98..089e74ec3f9a 100644 --- a/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\EnumNode; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; class EnumNodeTest extends TestCase { @@ -49,7 +50,7 @@ public function testConstructionWithNullName() public function testFinalizeWithInvalidValue() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('The value "foobar" is not allowed for path "foo". Permissible values: "foo", "bar"'); $node = new EnumNode('foo', null, ['foo', 'bar']); $node->finalize('foobar'); diff --git a/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php index a22550bcc8fd..68ed8a752120 100644 --- a/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Config\Tests\Definition; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Definition\Exception\InvalidTypeException; use Symfony\Component\Config\Definition\FloatNode; class FloatNodeTest extends TestCase @@ -57,7 +58,7 @@ public function getValidValues() */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidTypeException::class); + $this->expectException(InvalidTypeException::class); $node = new FloatNode('test'); $node->normalize($value); } diff --git a/src/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.php index 2bc7db02ec44..c4dd57b8f45f 100644 --- a/src/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Config\Tests\Definition; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Definition\Exception\InvalidTypeException; use Symfony\Component\Config\Definition\IntegerNode; class IntegerNodeTest extends TestCase @@ -52,7 +53,7 @@ public function getValidValues() */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidTypeException::class); + $this->expectException(InvalidTypeException::class); $node = new IntegerNode('test'); $node->normalize($value); } diff --git a/src/Symfony/Component/Config/Tests/Definition/MergeTest.php b/src/Symfony/Component/Config/Tests/Definition/MergeTest.php index e9d87d9b2a6d..bc7d9670406b 100644 --- a/src/Symfony/Component/Config/Tests/Definition/MergeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/MergeTest.php @@ -13,12 +13,14 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\Builder\TreeBuilder; +use Symfony\Component\Config\Definition\Exception\ForbiddenOverwriteException; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; class MergeTest extends TestCase { public function testForbiddenOverwrite() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\ForbiddenOverwriteException::class); + $this->expectException(ForbiddenOverwriteException::class); $tb = new TreeBuilder('root', 'array'); $tree = $tb ->getRootNode() @@ -92,7 +94,7 @@ public function testUnsetKey() public function testDoesNotAllowNewKeysInSubsequentConfigs() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $tb = new TreeBuilder('root', 'array'); $tree = $tb ->getRootNode() diff --git a/src/Symfony/Component/Config/Tests/Definition/NormalizationTest.php b/src/Symfony/Component/Config/Tests/Definition/NormalizationTest.php index c5fd94875bc8..3fecac2e3e7e 100644 --- a/src/Symfony/Component/Config/Tests/Definition/NormalizationTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/NormalizationTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\Builder\TreeBuilder; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\Config\Definition\NodeInterface; class NormalizationTest extends TestCase @@ -171,7 +172,7 @@ public function getNumericKeysTests() public function testNonAssociativeArrayThrowsExceptionIfAttributeNotSet() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('The attribute "id" must be set for path "root.thing".'); $denormalized = [ 'thing' => [ diff --git a/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php index 892c91d63ff2..0eb66963ebe5 100644 --- a/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\ArrayNode; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; +use Symfony\Component\Config\Definition\Exception\InvalidTypeException; use Symfony\Component\Config\Definition\ScalarNode; class ScalarNodeTest extends TestCase @@ -77,7 +79,7 @@ public function testSetDeprecated() */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidTypeException::class); + $this->expectException(InvalidTypeException::class); $node = new ScalarNode('test'); $node->normalize($value); } @@ -95,7 +97,7 @@ public function testNormalizeThrowsExceptionWithoutHint() { $node = new ScalarNode('test'); - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidTypeException::class); + $this->expectException(InvalidTypeException::class); $this->expectExceptionMessage('Invalid type for path "test". Expected scalar, but got array.'); $node->normalize([]); @@ -106,7 +108,7 @@ public function testNormalizeThrowsExceptionWithErrorMessage() $node = new ScalarNode('test'); $node->setInfo('"the test value"'); - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidTypeException::class); + $this->expectException(InvalidTypeException::class); $this->expectExceptionMessage("Invalid type for path \"test\". Expected scalar, but got array.\nHint: \"the test value\""); $node->normalize([]); @@ -145,7 +147,7 @@ public function getValidNonEmptyValues() */ public function testNotAllowedEmptyValuesThrowException($value) { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $node = new ScalarNode('test'); $node->setAllowEmptyValue(false); $node->finalize($value); diff --git a/src/Symfony/Component/Config/Tests/FileLocatorTest.php b/src/Symfony/Component/Config/Tests/FileLocatorTest.php index 4bdc945125f6..44ef5ac9e3eb 100644 --- a/src/Symfony/Component/Config/Tests/FileLocatorTest.php +++ b/src/Symfony/Component/Config/Tests/FileLocatorTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Config\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Exception\FileLocatorFileNotFoundException; use Symfony\Component\Config\FileLocator; class FileLocatorTest extends TestCase @@ -88,7 +89,7 @@ public function testLocate() public function testLocateThrowsAnExceptionIfTheFileDoesNotExists() { - $this->expectException(\Symfony\Component\Config\Exception\FileLocatorFileNotFoundException::class); + $this->expectException(FileLocatorFileNotFoundException::class); $this->expectExceptionMessage('The file "foobar.xml" does not exist'); $loader = new FileLocator([__DIR__.'/Fixtures']); @@ -97,7 +98,7 @@ public function testLocateThrowsAnExceptionIfTheFileDoesNotExists() public function testLocateThrowsAnExceptionIfTheFileDoesNotExistsInAbsolutePath() { - $this->expectException(\Symfony\Component\Config\Exception\FileLocatorFileNotFoundException::class); + $this->expectException(FileLocatorFileNotFoundException::class); $loader = new FileLocator([__DIR__.'/Fixtures']); $loader->locate(__DIR__.'/Fixtures/foobar.xml', __DIR__); diff --git a/src/Symfony/Component/Config/Tests/Loader/DelegatingLoaderTest.php b/src/Symfony/Component/Config/Tests/Loader/DelegatingLoaderTest.php index 2de74c402285..4f689775f7b1 100644 --- a/src/Symfony/Component/Config/Tests/Loader/DelegatingLoaderTest.php +++ b/src/Symfony/Component/Config/Tests/Loader/DelegatingLoaderTest.php @@ -12,7 +12,9 @@ namespace Symfony\Component\Config\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Exception\LoaderLoadException; use Symfony\Component\Config\Loader\DelegatingLoader; +use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\Config\Loader\LoaderResolver; class DelegatingLoaderTest extends TestCase @@ -34,12 +36,12 @@ public function testGetSetResolver() public function testSupports() { - $loader1 = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $loader1 = $this->createMock(LoaderInterface::class); $loader1->expects($this->once())->method('supports')->willReturn(true); $loader = new DelegatingLoader(new LoaderResolver([$loader1])); $this->assertTrue($loader->supports('foo.xml'), '->supports() returns true if the resource is loadable'); - $loader1 = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $loader1 = $this->createMock(LoaderInterface::class); $loader1->expects($this->once())->method('supports')->willReturn(false); $loader = new DelegatingLoader(new LoaderResolver([$loader1])); $this->assertFalse($loader->supports('foo.foo'), '->supports() returns false if the resource is not loadable'); @@ -47,7 +49,7 @@ public function testSupports() public function testLoad() { - $loader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loader->expects($this->once())->method('supports')->willReturn(true); $loader->expects($this->once())->method('load'); $resolver = new LoaderResolver([$loader]); @@ -58,8 +60,8 @@ public function testLoad() public function testLoadThrowsAnExceptionIfTheResourceCannotBeLoaded() { - $this->expectException(\Symfony\Component\Config\Exception\LoaderLoadException::class); - $loader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $this->expectException(LoaderLoadException::class); + $loader = $this->createMock(LoaderInterface::class); $loader->expects($this->once())->method('supports')->willReturn(false); $resolver = new LoaderResolver([$loader]); $loader = new DelegatingLoader($resolver); diff --git a/src/Symfony/Component/Config/Tests/Loader/FileLoaderTest.php b/src/Symfony/Component/Config/Tests/Loader/FileLoaderTest.php index 61fdabe0395c..5fc8ce0a829d 100644 --- a/src/Symfony/Component/Config/Tests/Loader/FileLoaderTest.php +++ b/src/Symfony/Component/Config/Tests/Loader/FileLoaderTest.php @@ -12,7 +12,9 @@ namespace Symfony\Component\Config\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Exception\FileLoaderImportCircularReferenceException; use Symfony\Component\Config\FileLocator; +use Symfony\Component\Config\FileLocatorInterface; use Symfony\Component\Config\Loader\FileLoader; use Symfony\Component\Config\Loader\LoaderResolver; @@ -20,9 +22,9 @@ class FileLoaderTest extends TestCase { public function testImportWithFileLocatorDelegation() { - $locatorMock = $this->getMockBuilder(\Symfony\Component\Config\FileLocatorInterface::class)->getMock(); + $locatorMock = $this->createMock(FileLocatorInterface::class); - $locatorMockForAdditionalLoader = $this->getMockBuilder(\Symfony\Component\Config\FileLocatorInterface::class)->getMock(); + $locatorMockForAdditionalLoader = $this->createMock(FileLocatorInterface::class); $locatorMockForAdditionalLoader->expects($this->any())->method('locate')->will($this->onConsecutiveCalls( ['path/to/file1'], // Default ['path/to/file1', 'path/to/file2'], // First is imported @@ -55,7 +57,7 @@ public function testImportWithFileLocatorDelegation() $fileLoader->import('my_resource'); $this->fail('->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\Config\Exception\FileLoaderImportCircularReferenceException::class, $e, '->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading'); + $this->assertInstanceOf(FileLoaderImportCircularReferenceException::class, $e, '->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading'); } // Check exception throws if all files are already loading @@ -64,13 +66,13 @@ public function testImportWithFileLocatorDelegation() $fileLoader->import('my_resource'); $this->fail('->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\Config\Exception\FileLoaderImportCircularReferenceException::class, $e, '->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading'); + $this->assertInstanceOf(FileLoaderImportCircularReferenceException::class, $e, '->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading'); } } public function testImportWithGlobLikeResource() { - $locatorMock = $this->getMockBuilder(\Symfony\Component\Config\FileLocatorInterface::class)->getMock(); + $locatorMock = $this->createMock(FileLocatorInterface::class); $locatorMock->expects($this->once())->method('locate')->willReturn(''); $loader = new TestFileLoader($locatorMock); @@ -79,7 +81,7 @@ public function testImportWithGlobLikeResource() public function testImportWithGlobLikeResourceWhichContainsSlashes() { - $locatorMock = $this->getMockBuilder(\Symfony\Component\Config\FileLocatorInterface::class)->getMock(); + $locatorMock = $this->createMock(FileLocatorInterface::class); $locatorMock->expects($this->once())->method('locate')->willReturn(''); $loader = new TestFileLoader($locatorMock); @@ -88,7 +90,7 @@ public function testImportWithGlobLikeResourceWhichContainsSlashes() public function testImportWithGlobLikeResourceWhichContainsMultipleLines() { - $locatorMock = $this->getMockBuilder(\Symfony\Component\Config\FileLocatorInterface::class)->getMock(); + $locatorMock = $this->createMock(FileLocatorInterface::class); $loader = new TestFileLoader($locatorMock); $this->assertSame("foo\nfoobar[foo]", $loader->import("foo\nfoobar[foo]")); @@ -96,7 +98,7 @@ public function testImportWithGlobLikeResourceWhichContainsMultipleLines() public function testImportWithGlobLikeResourceWhichContainsSlashesAndMultipleLines() { - $locatorMock = $this->getMockBuilder(\Symfony\Component\Config\FileLocatorInterface::class)->getMock(); + $locatorMock = $this->createMock(FileLocatorInterface::class); $loader = new TestFileLoader($locatorMock); $this->assertSame("foo\nfoo/bar[foo]", $loader->import("foo\nfoo/bar[foo]")); @@ -104,7 +106,7 @@ public function testImportWithGlobLikeResourceWhichContainsSlashesAndMultipleLin public function testImportWithNoGlobMatch() { - $locatorMock = $this->getMockBuilder(\Symfony\Component\Config\FileLocatorInterface::class)->getMock(); + $locatorMock = $this->createMock(FileLocatorInterface::class); $locatorMock->expects($this->once())->method('locate')->willReturn(''); $loader = new TestFileLoader($locatorMock); diff --git a/src/Symfony/Component/Config/Tests/Loader/LoaderResolverTest.php b/src/Symfony/Component/Config/Tests/Loader/LoaderResolverTest.php index 90d1ef09111b..afd42a995e7b 100644 --- a/src/Symfony/Component/Config/Tests/Loader/LoaderResolverTest.php +++ b/src/Symfony/Component/Config/Tests/Loader/LoaderResolverTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Config\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\Config\Loader\LoaderResolver; class LoaderResolverTest extends TestCase @@ -19,7 +20,7 @@ class LoaderResolverTest extends TestCase public function testConstructor() { $resolver = new LoaderResolver([ - $loader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(), + $loader = $this->createMock(LoaderInterface::class), ]); $this->assertEquals([$loader], $resolver->getLoaders(), '__construct() takes an array of loaders as its first argument'); @@ -27,11 +28,11 @@ public function testConstructor() public function testResolve() { - $loader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $resolver = new LoaderResolver([$loader]); $this->assertFalse($resolver->resolve('foo.foo'), '->resolve() returns false if no loader is able to load the resource'); - $loader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loader->expects($this->once())->method('supports')->willReturn(true); $resolver = new LoaderResolver([$loader]); $this->assertEquals($loader, $resolver->resolve(function () {}), '->resolve() returns the loader for the given resource'); @@ -40,7 +41,7 @@ public function testResolve() public function testLoaders() { $resolver = new LoaderResolver(); - $resolver->addLoader($loader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock()); + $resolver->addLoader($loader = $this->createMock(LoaderInterface::class)); $this->assertEquals([$loader], $resolver->getLoaders(), 'addLoader() adds a loader'); } diff --git a/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php b/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php index 7eb50d62a040..0a4ea0e2fb91 100644 --- a/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php +++ b/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php @@ -12,13 +12,16 @@ namespace Symfony\Component\Config\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Exception\LoaderLoadException; use Symfony\Component\Config\Loader\Loader; +use Symfony\Component\Config\Loader\LoaderInterface; +use Symfony\Component\Config\Loader\LoaderResolverInterface; class LoaderTest extends TestCase { public function testGetSetResolver() { - $resolver = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderResolverInterface::class)->getMock(); + $resolver = $this->createMock(LoaderResolverInterface::class); $loader = new ProjectLoader1(); $loader->setResolver($resolver); @@ -28,9 +31,9 @@ public function testGetSetResolver() public function testResolve() { - $resolvedLoader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $resolvedLoader = $this->createMock(LoaderInterface::class); - $resolver = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderResolverInterface::class)->getMock(); + $resolver = $this->createMock(LoaderResolverInterface::class); $resolver->expects($this->once()) ->method('resolve') ->with('foo.xml') @@ -45,8 +48,8 @@ public function testResolve() public function testResolveWhenResolverCannotFindLoader() { - $this->expectException(\Symfony\Component\Config\Exception\LoaderLoadException::class); - $resolver = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderResolverInterface::class)->getMock(); + $this->expectException(LoaderLoadException::class); + $resolver = $this->createMock(LoaderResolverInterface::class); $resolver->expects($this->once()) ->method('resolve') ->with('FOOBAR') @@ -60,13 +63,13 @@ public function testResolveWhenResolverCannotFindLoader() public function testImport() { - $resolvedLoader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $resolvedLoader = $this->createMock(LoaderInterface::class); $resolvedLoader->expects($this->once()) ->method('load') ->with('foo') ->willReturn('yes'); - $resolver = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderResolverInterface::class)->getMock(); + $resolver = $this->createMock(LoaderResolverInterface::class); $resolver->expects($this->once()) ->method('resolve') ->with('foo') @@ -80,13 +83,13 @@ public function testImport() public function testImportWithType() { - $resolvedLoader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $resolvedLoader = $this->createMock(LoaderInterface::class); $resolvedLoader->expects($this->once()) ->method('load') ->with('foo', 'bar') ->willReturn('yes'); - $resolver = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderResolverInterface::class)->getMock(); + $resolver = $this->createMock(LoaderResolverInterface::class); $resolver->expects($this->once()) ->method('resolve') ->with('foo', 'bar') diff --git a/src/Symfony/Component/Config/Tests/ResourceCheckerConfigCacheTest.php b/src/Symfony/Component/Config/Tests/ResourceCheckerConfigCacheTest.php index bd66e615bf6b..8747cbecf435 100644 --- a/src/Symfony/Component/Config/Tests/ResourceCheckerConfigCacheTest.php +++ b/src/Symfony/Component/Config/Tests/ResourceCheckerConfigCacheTest.php @@ -46,7 +46,7 @@ public function testGetPath() public function testCacheIsNotFreshIfEmpty() { - $checker = $this->getMockBuilder(ResourceCheckerInterface::class)->getMock() + $checker = $this->createMock(ResourceCheckerInterface::class) ->expects($this->never())->method('supports'); /* If there is nothing in the cache, it needs to be filled (and thus it's not fresh). @@ -83,7 +83,7 @@ public function testResourcesWithoutcheckersAreIgnoredAndConsideredFresh() public function testIsFreshWithchecker() { - $checker = $this->getMockBuilder(ResourceCheckerInterface::class)->getMock(); + $checker = $this->createMock(ResourceCheckerInterface::class); $checker->expects($this->once()) ->method('supports') @@ -101,7 +101,7 @@ public function testIsFreshWithchecker() public function testIsNotFreshWithchecker() { - $checker = $this->getMockBuilder(ResourceCheckerInterface::class)->getMock(); + $checker = $this->createMock(ResourceCheckerInterface::class); $checker->expects($this->once()) ->method('supports') @@ -119,7 +119,7 @@ public function testIsNotFreshWithchecker() public function testCacheIsNotFreshWhenUnserializeFails() { - $checker = $this->getMockBuilder(ResourceCheckerInterface::class)->getMock(); + $checker = $this->createMock(ResourceCheckerInterface::class); $cache = new ResourceCheckerConfigCache($this->cacheFile, [$checker]); $cache->write('foo', [new FileResource(__FILE__)]); @@ -139,8 +139,7 @@ public function testCacheKeepsContent() public function testCacheIsNotFreshIfNotExistsMetaFile() { - $checker = $this->getMockBuilder(ResourceCheckerInterface::class - )->getMock(); + $checker = $this->createMock(ResourceCheckerInterface::class); $cache = new ResourceCheckerConfigCache($this->cacheFile, [$checker]); $cache->write('foo', [new FileResource(__FILE__)]); diff --git a/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php b/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php index 386d97c99ad2..481603763aa2 100644 --- a/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php +++ b/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Config\Tests\Util; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Util\Exception\InvalidXmlException; use Symfony\Component\Config\Util\XmlUtils; class XmlUtilsTest extends TestCase @@ -74,7 +75,7 @@ public function testLoadFile() $this->assertStringContainsString('XSD file or callable', $e->getMessage()); } - $mock = $this->getMockBuilder(Validator::class)->getMock(); + $mock = $this->createMock(Validator::class); $mock->expects($this->exactly(2))->method('validate')->will($this->onConsecutiveCalls(false, true)); try { @@ -90,11 +91,11 @@ public function testLoadFile() public function testParseWithInvalidValidatorCallable() { - $this->expectException(\Symfony\Component\Config\Util\Exception\InvalidXmlException::class); + $this->expectException(InvalidXmlException::class); $this->expectExceptionMessage('The XML is not valid'); $fixtures = __DIR__.'/../Fixtures/Util/'; - $mock = $this->getMockBuilder(Validator::class)->getMock(); + $mock = $this->createMock(Validator::class); $mock->expects($this->once())->method('validate')->willReturn(false); XmlUtils::parse(file_get_contents($fixtures.'valid.xml'), [$mock, 'validate']); diff --git a/src/Symfony/Component/Console/Tests/ApplicationTest.php b/src/Symfony/Component/Console/Tests/ApplicationTest.php index 004b40955ddd..d293697d422c 100644 --- a/src/Symfony/Component/Console/Tests/ApplicationTest.php +++ b/src/Symfony/Component/Console/Tests/ApplicationTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Application; use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Command\HelpCommand; use Symfony\Component\Console\CommandLoader\FactoryCommandLoader; use Symfony\Component\Console\DependencyInjection\AddConsoleCommandPass; use Symfony\Component\Console\Event\ConsoleCommandEvent; @@ -29,6 +30,7 @@ use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Console\Output\NullOutput; use Symfony\Component\Console\Output\Output; use Symfony\Component\Console\Output\OutputInterface; @@ -134,7 +136,7 @@ public function testAll() { $application = new Application(); $commands = $application->all(); - $this->assertInstanceOf(\Symfony\Component\Console\Command\HelpCommand::class, $commands['help'], '->all() returns the registered commands'); + $this->assertInstanceOf(HelpCommand::class, $commands['help'], '->all() returns the registered commands'); $application->add(new \FooCommand()); $commands = $application->all('foo'); @@ -145,7 +147,7 @@ public function testAllWithCommandLoader() { $application = new Application(); $commands = $application->all(); - $this->assertInstanceOf(\Symfony\Component\Console\Command\HelpCommand::class, $commands['help'], '->all() returns the registered commands'); + $this->assertInstanceOf(HelpCommand::class, $commands['help'], '->all() returns the registered commands'); $application->add(new \FooCommand()); $commands = $application->all('foo'); @@ -229,7 +231,7 @@ public function testHasGet() $p->setAccessible(true); $p->setValue($application, true); $command = $application->get('foo:bar'); - $this->assertInstanceOf(\Symfony\Component\Console\Command\HelpCommand::class, $command, '->get() returns the help command if --help is provided as the input'); + $this->assertInstanceOf(HelpCommand::class, $command, '->get() returns the help command if --help is provided as the input'); } public function testHasGetWithCommandLoader() @@ -351,7 +353,7 @@ public function testFind() $application->add(new \FooCommand()); $this->assertInstanceOf(\FooCommand::class, $application->find('foo:bar'), '->find() returns a command if its name exists'); - $this->assertInstanceOf(\Symfony\Component\Console\Command\HelpCommand::class, $application->find('h'), '->find() returns a command if its name exists'); + $this->assertInstanceOf(HelpCommand::class, $application->find('h'), '->find() returns a command if its name exists'); $this->assertInstanceOf(\FooCommand::class, $application->find('f:bar'), '->find() returns a command if the abbreviation for the namespace exists'); $this->assertInstanceOf(\FooCommand::class, $application->find('f:b'), '->find() returns a command if the abbreviation for the namespace and the command name exist'); $this->assertInstanceOf(\FooCommand::class, $application->find('a'), '->find() returns a command if the abbreviation exists for an alias'); @@ -398,7 +400,7 @@ public function testFindWithCommandLoader() ])); $this->assertInstanceOf(\FooCommand::class, $application->find('foo:bar'), '->find() returns a command if its name exists'); - $this->assertInstanceOf(\Symfony\Component\Console\Command\HelpCommand::class, $application->find('h'), '->find() returns a command if its name exists'); + $this->assertInstanceOf(HelpCommand::class, $application->find('h'), '->find() returns a command if its name exists'); $this->assertInstanceOf(\FooCommand::class, $application->find('f:bar'), '->find() returns a command if the abbreviation for the namespace exists'); $this->assertInstanceOf(\FooCommand::class, $application->find('f:b'), '->find() returns a command if the abbreviation for the namespace and the command name exist'); $this->assertInstanceOf(\FooCommand::class, $application->find('a'), '->find() returns a command if the abbreviation exists for an alias'); @@ -951,7 +953,7 @@ public function testRun() ob_end_clean(); $this->assertInstanceOf(ArgvInput::class, $command->input, '->run() creates an ArgvInput by default if none is given'); - $this->assertInstanceOf(\Symfony\Component\Console\Output\ConsoleOutput::class, $command->output, '->run() creates a ConsoleOutput by default if none is given'); + $this->assertInstanceOf(ConsoleOutput::class, $command->output, '->run() creates a ConsoleOutput by default if none is given'); $application = new Application(); $application->setAutoExit(false); diff --git a/src/Symfony/Component/Console/Tests/Command/CommandTest.php b/src/Symfony/Component/Console/Tests/Command/CommandTest.php index 9e1ae05eb171..10a476d192e3 100644 --- a/src/Symfony/Component/Console/Tests/Command/CommandTest.php +++ b/src/Symfony/Component/Console/Tests/Command/CommandTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Application; use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\InvalidOptionException; use Symfony\Component\Console\Helper\FormatterHelper; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputDefinition; @@ -293,7 +294,7 @@ public function testExecuteMethodNeedsToBeOverridden() public function testRunWithInvalidOption() { - $this->expectException(\Symfony\Component\Console\Exception\InvalidOptionException::class); + $this->expectException(InvalidOptionException::class); $this->expectExceptionMessage('The "--bar" option does not exist.'); $command = new \TestCommand(); $tester = new CommandTester($command); diff --git a/src/Symfony/Component/Console/Tests/CommandLoader/ContainerCommandLoaderTest.php b/src/Symfony/Component/Console/Tests/CommandLoader/ContainerCommandLoaderTest.php index 67b2d5ceec16..e7f138933ae7 100644 --- a/src/Symfony/Component/Console/Tests/CommandLoader/ContainerCommandLoaderTest.php +++ b/src/Symfony/Component/Console/Tests/CommandLoader/ContainerCommandLoaderTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\CommandLoader\ContainerCommandLoader; +use Symfony\Component\Console\Exception\CommandNotFoundException; use Symfony\Component\DependencyInjection\ServiceLocator; class ContainerCommandLoaderTest extends TestCase @@ -43,7 +44,7 @@ public function testGet() public function testGetUnknownCommandThrows() { - $this->expectException(\Symfony\Component\Console\Exception\CommandNotFoundException::class); + $this->expectException(CommandNotFoundException::class); (new ContainerCommandLoader(new ServiceLocator([]), []))->get('unknown'); } diff --git a/src/Symfony/Component/Console/Tests/CommandLoader/FactoryCommandLoaderTest.php b/src/Symfony/Component/Console/Tests/CommandLoader/FactoryCommandLoaderTest.php index 8546ae669c11..aebb429e652f 100644 --- a/src/Symfony/Component/Console/Tests/CommandLoader/FactoryCommandLoaderTest.php +++ b/src/Symfony/Component/Console/Tests/CommandLoader/FactoryCommandLoaderTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\CommandLoader\FactoryCommandLoader; +use Symfony\Component\Console\Exception\CommandNotFoundException; class FactoryCommandLoaderTest extends TestCase { @@ -42,7 +43,7 @@ public function testGet() public function testGetUnknownCommandThrows() { - $this->expectException(\Symfony\Component\Console\Exception\CommandNotFoundException::class); + $this->expectException(CommandNotFoundException::class); (new FactoryCommandLoader([]))->get('unknown'); } diff --git a/src/Symfony/Component/Console/Tests/EventListener/ErrorListenerTest.php b/src/Symfony/Component/Console/Tests/EventListener/ErrorListenerTest.php index 68b4b3a3e165..ce3df1a0ec7b 100644 --- a/src/Symfony/Component/Console/Tests/EventListener/ErrorListenerTest.php +++ b/src/Symfony/Component/Console/Tests/EventListener/ErrorListenerTest.php @@ -117,7 +117,7 @@ public function testCommandNameIsDisplayedForNonStringableInput() ; $listener = new ErrorListener($logger); - $listener->onConsoleTerminate($this->getConsoleTerminateEvent($this->getMockBuilder(InputInterface::class)->getMock(), 255)); + $listener->onConsoleTerminate($this->getConsoleTerminateEvent($this->createMock(InputInterface::class), 255)); } private function getLogger() @@ -132,7 +132,7 @@ private function getConsoleTerminateEvent(InputInterface $input, $exitCode) private function getOutput() { - return $this->getMockBuilder(OutputInterface::class)->getMock(); + return $this->createMock(OutputInterface::class); } } diff --git a/src/Symfony/Component/Console/Tests/Helper/AbstractQuestionHelperTest.php b/src/Symfony/Component/Console/Tests/Helper/AbstractQuestionHelperTest.php index f12566dedd65..3da121624443 100644 --- a/src/Symfony/Component/Console/Tests/Helper/AbstractQuestionHelperTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/AbstractQuestionHelperTest.php @@ -18,7 +18,7 @@ abstract class AbstractQuestionHelperTest extends TestCase { protected function createStreamableInputInterfaceMock($stream = null, $interactive = true) { - $mock = $this->getMockBuilder(StreamableInputInterface::class)->getMock(); + $mock = $this->createMock(StreamableInputInterface::class); $mock->expects($this->any()) ->method('isInteractive') ->willReturn($interactive); diff --git a/src/Symfony/Component/Console/Tests/Helper/DumperNativeFallbackTest.php b/src/Symfony/Component/Console/Tests/Helper/DumperNativeFallbackTest.php index b0d13cc1b75e..906d322b665d 100644 --- a/src/Symfony/Component/Console/Tests/Helper/DumperNativeFallbackTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/DumperNativeFallbackTest.php @@ -37,7 +37,7 @@ public static function tearDownAfterClass(): void */ public function testInvoke($variable, $primitiveString) { - $dumper = new Dumper($this->getMockBuilder(OutputInterface::class)->getMock()); + $dumper = new Dumper($this->createMock(OutputInterface::class)); $this->assertSame($primitiveString, $dumper($variable)); } diff --git a/src/Symfony/Component/Console/Tests/Helper/DumperTest.php b/src/Symfony/Component/Console/Tests/Helper/DumperTest.php index 8791b08b96b8..e491422b0fbb 100644 --- a/src/Symfony/Component/Console/Tests/Helper/DumperTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/DumperTest.php @@ -37,7 +37,7 @@ public static function tearDownAfterClass(): void */ public function testInvoke($variable) { - $output = $this->getMockBuilder(OutputInterface::class)->getMock(); + $output = $this->createMock(OutputInterface::class); $output->method('isDecorated')->willReturn(false); $dumper = new Dumper($output); diff --git a/src/Symfony/Component/Console/Tests/Helper/HelperSetTest.php b/src/Symfony/Component/Console/Tests/Helper/HelperSetTest.php index 707a190cf4a1..38cfc27a194b 100644 --- a/src/Symfony/Component/Console/Tests/Helper/HelperSetTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/HelperSetTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\ExceptionInterface; use Symfony\Component\Console\Helper\HelperInterface; use Symfony\Component\Console\Helper\HelperSet; @@ -68,7 +69,7 @@ public function testGet() $this->fail('->get() throws InvalidArgumentException when helper not found'); } catch (\Exception $e) { $this->assertInstanceOf(\InvalidArgumentException::class, $e, '->get() throws InvalidArgumentException when helper not found'); - $this->assertInstanceOf(\Symfony\Component\Console\Exception\ExceptionInterface::class, $e, '->get() throws domain specific exception when helper not found'); + $this->assertInstanceOf(ExceptionInterface::class, $e, '->get() throws domain specific exception when helper not found'); $this->assertStringContainsString('The helper "foo" is not defined.', $e->getMessage(), '->get() throws InvalidArgumentException when helper not found'); } } @@ -112,7 +113,7 @@ public function testIteration() private function getGenericMockHelper($name, HelperSet $helperset = null) { - $mock_helper = $this->getMockBuilder(HelperInterface::class)->getMock(); + $mock_helper = $this->createMock(HelperInterface::class); $mock_helper->expects($this->any()) ->method('getName') ->willReturn($name); diff --git a/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php b/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php index 5db0ded77291..bba71cc5942b 100644 --- a/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php @@ -13,10 +13,12 @@ use Symfony\Component\Console\Application; use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\MissingInputException; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Helper\FormatterHelper; use Symfony\Component\Console\Helper\HelperSet; use Symfony\Component\Console\Helper\QuestionHelper; +use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\StreamOutput; use Symfony\Component\Console\Question\ChoiceQuestion; @@ -685,7 +687,7 @@ public function testChoiceOutputFormattingQuestionForUtf8Keys() ' [żółw ] bar', ' [łabądź] baz', ]; - $output = $this->getMockBuilder(OutputInterface::class)->getMock(); + $output = $this->createMock(OutputInterface::class); $output->method('getFormatter')->willReturn(new OutputFormatter()); $dialog = new QuestionHelper(); @@ -700,7 +702,7 @@ public function testChoiceOutputFormattingQuestionForUtf8Keys() public function testAskThrowsExceptionOnMissingInput() { - $this->expectException(\Symfony\Component\Console\Exception\MissingInputException::class); + $this->expectException(MissingInputException::class); $this->expectExceptionMessage('Aborted.'); $dialog = new QuestionHelper(); $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new Question('What\'s your name?')); @@ -708,7 +710,7 @@ public function testAskThrowsExceptionOnMissingInput() public function testAskThrowsExceptionOnMissingInputForChoiceQuestion() { - $this->expectException(\Symfony\Component\Console\Exception\MissingInputException::class); + $this->expectException(MissingInputException::class); $this->expectExceptionMessage('Aborted.'); $dialog = new QuestionHelper(); $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new ChoiceQuestion('Choice', ['a', 'b'])); @@ -716,7 +718,7 @@ public function testAskThrowsExceptionOnMissingInputForChoiceQuestion() public function testAskThrowsExceptionOnMissingInputWithValidator() { - $this->expectException(\Symfony\Component\Console\Exception\MissingInputException::class); + $this->expectException(MissingInputException::class); $this->expectExceptionMessage('Aborted.'); $dialog = new QuestionHelper(); @@ -878,7 +880,7 @@ protected function createOutputInterface() protected function createInputInterfaceMock($interactive = true) { - $mock = $this->getMockBuilder(\Symfony\Component\Console\Input\InputInterface::class)->getMock(); + $mock = $this->createMock(InputInterface::class); $mock->expects($this->any()) ->method('isInteractive') ->willReturn($interactive); diff --git a/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php b/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php index d7fcf7ecfd92..fd5442b7f4b9 100644 --- a/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php @@ -2,9 +2,11 @@ namespace Symfony\Component\Console\Tests\Helper; +use Symfony\Component\Console\Exception\RuntimeException; use Symfony\Component\Console\Helper\FormatterHelper; use Symfony\Component\Console\Helper\HelperSet; use Symfony\Component\Console\Helper\SymfonyQuestionHelper; +use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\StreamOutput; use Symfony\Component\Console\Question\ChoiceQuestion; use Symfony\Component\Console\Question\Question; @@ -124,7 +126,7 @@ public function testLabelTrailingBackslash() public function testAskThrowsExceptionOnMissingInput() { - $this->expectException(\Symfony\Component\Console\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Aborted.'); $dialog = new SymfonyQuestionHelper(); $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new Question('What\'s your name?')); @@ -149,7 +151,7 @@ public function testChoiceQuestionPadding() [foo ] foo [żółw ] bar [łabądź] baz - > + > EOT , $output, true); } @@ -168,7 +170,7 @@ public function testChoiceQuestionCustomPrompt() $this->assertOutputContains(<<ccc> + >ccc> EOT , $output, true); } @@ -192,7 +194,7 @@ protected function createOutputInterface() protected function createInputInterfaceMock($interactive = true) { - $mock = $this->getMockBuilder(\Symfony\Component\Console\Input\InputInterface::class)->getMock(); + $mock = $this->createMock(InputInterface::class); $mock->expects($this->any()) ->method('isInteractive') ->willReturn($interactive); diff --git a/src/Symfony/Component/Console/Tests/Helper/TableTest.php b/src/Symfony/Component/Console/Tests/Helper/TableTest.php index 3ad71062cfaf..d02d6ea42e30 100644 --- a/src/Symfony/Component/Console/Tests/Helper/TableTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/TableTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\Console\Tests\Helper; use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\RuntimeException; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Helper\TableCell; @@ -808,7 +810,7 @@ public function testColumnStyle() public function testThrowsWhenTheCellInAnArray() { - $this->expectException(\Symfony\Component\Console\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('A cell must be a TableCell, a scalar or an object implementing "__toString()", "array" given.'); $table = new Table($output = $this->getOutputStream()); $table @@ -983,7 +985,7 @@ public function testSectionOutputWithoutDecoration() public function testAppendRowWithoutSectionOutput() { - $this->expectException(\Symfony\Component\Console\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Output should be an instance of "Symfony\Component\Console\Output\ConsoleSectionOutput" when calling "Symfony\Component\Console\Helper\Table::appendRow".'); $table = new Table($this->getOutputStream()); @@ -1024,7 +1026,7 @@ public function testSectionOutputHandlesZeroRowsAfterRender() public function testIsNotDefinedStyleException() { - $this->expectException(\Symfony\Component\Console\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Style "absent" is not defined.'); $table = new Table($this->getOutputStream()); $table->setStyle('absent'); @@ -1032,7 +1034,7 @@ public function testIsNotDefinedStyleException() public function testGetStyleDefinition() { - $this->expectException(\Symfony\Component\Console\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Style "absent" is not defined.'); Table::getStyleDefinition('absent'); } diff --git a/src/Symfony/Component/Console/Tests/Input/StringInputTest.php b/src/Symfony/Component/Console/Tests/Input/StringInputTest.php index bcc43e431a8b..f781b7ccfa17 100644 --- a/src/Symfony/Component/Console/Tests/Input/StringInputTest.php +++ b/src/Symfony/Component/Console/Tests/Input/StringInputTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Console\Tests\Input; use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Input\ArgvInput; use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\StringInput; @@ -24,7 +25,7 @@ class StringInputTest extends TestCase public function testTokenize($input, $tokens, $message) { $input = new StringInput($input); - $r = new \ReflectionClass(\Symfony\Component\Console\Input\ArgvInput::class); + $r = new \ReflectionClass(ArgvInput::class); $p = $r->getProperty('tokens'); $p->setAccessible(true); $this->assertEquals($tokens, $p->getValue($input), $message); diff --git a/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php b/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php index ebf2d7aa1392..3585bde63a12 100644 --- a/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php +++ b/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Console\Tests\Logger; use PHPUnit\Framework\TestCase; +use Psr\Log\InvalidArgumentException; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; use Symfony\Component\Console\Logger\ConsoleLogger; @@ -138,7 +139,7 @@ public function provideLevelsAndMessages() public function testThrowsOnInvalidLevel() { - $this->expectException(\Psr\Log\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $logger = $this->getLogger(); $logger->log('invalid level', 'Foo'); } diff --git a/src/Symfony/Component/Console/Tests/Output/ConsoleSectionOutputTest.php b/src/Symfony/Component/Console/Tests/Output/ConsoleSectionOutputTest.php index f5ea668f498d..206b201bc14f 100644 --- a/src/Symfony/Component/Console/Tests/Output/ConsoleSectionOutputTest.php +++ b/src/Symfony/Component/Console/Tests/Output/ConsoleSectionOutputTest.php @@ -147,7 +147,7 @@ public function testClearSectionContainingQuestion() fwrite($inputStream, "Batman & Robin\n"); rewind($inputStream); - $input = $this->getMockBuilder(StreamableInputInterface::class)->getMock(); + $input = $this->createMock(StreamableInputInterface::class); $input->expects($this->once())->method('isInteractive')->willReturn(true); $input->expects($this->once())->method('getStream')->willReturn($inputStream); diff --git a/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php b/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php index 2444d89ba001..201da6474995 100644 --- a/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php +++ b/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php @@ -83,9 +83,9 @@ public function inputCommandToOutputFilesProvider() public function testGetErrorStyle() { - $input = $this->getMockBuilder(InputInterface::class)->getMock(); + $input = $this->createMock(InputInterface::class); - $errorOutput = $this->getMockBuilder(OutputInterface::class)->getMock(); + $errorOutput = $this->createMock(OutputInterface::class); $errorOutput ->method('getFormatter') ->willReturn(new OutputFormatter()); @@ -93,7 +93,7 @@ public function testGetErrorStyle() ->expects($this->once()) ->method('write'); - $output = $this->getMockBuilder(ConsoleOutputInterface::class)->getMock(); + $output = $this->createMock(ConsoleOutputInterface::class); $output ->method('getFormatter') ->willReturn(new OutputFormatter()); @@ -108,12 +108,12 @@ public function testGetErrorStyle() public function testGetErrorStyleUsesTheCurrentOutputIfNoErrorOutputIsAvailable() { - $output = $this->getMockBuilder(OutputInterface::class)->getMock(); + $output = $this->createMock(OutputInterface::class); $output ->method('getFormatter') ->willReturn(new OutputFormatter()); - $style = new SymfonyStyle($this->getMockBuilder(InputInterface::class)->getMock(), $output); + $style = new SymfonyStyle($this->createMock(InputInterface::class), $output); $this->assertInstanceOf(SymfonyStyle::class, $style->getErrorStyle()); } diff --git a/src/Symfony/Component/CssSelector/Tests/CssSelectorConverterTest.php b/src/Symfony/Component/CssSelector/Tests/CssSelectorConverterTest.php index 718a5cd347bb..9656c5c24e36 100644 --- a/src/Symfony/Component/CssSelector/Tests/CssSelectorConverterTest.php +++ b/src/Symfony/Component/CssSelector/Tests/CssSelectorConverterTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\CssSelector\CssSelectorConverter; +use Symfony\Component\CssSelector\Exception\ParseException; class CssSelectorConverterTest extends TestCase { @@ -37,7 +38,7 @@ public function testCssToXPathXml() public function testParseExceptions() { - $this->expectException(\Symfony\Component\CssSelector\Exception\ParseException::class); + $this->expectException(ParseException::class); $this->expectExceptionMessage('Expected identifier, but found.'); $converter = new CssSelectorConverter(); $converter->toXPath('h1:'); diff --git a/src/Symfony/Component/CssSelector/Tests/Parser/TokenStreamTest.php b/src/Symfony/Component/CssSelector/Tests/Parser/TokenStreamTest.php index 85cabe9d7534..f50c8de8d00e 100644 --- a/src/Symfony/Component/CssSelector/Tests/Parser/TokenStreamTest.php +++ b/src/Symfony/Component/CssSelector/Tests/Parser/TokenStreamTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\CssSelector\Tests\Parser; use PHPUnit\Framework\TestCase; +use Symfony\Component\CssSelector\Exception\SyntaxErrorException; use Symfony\Component\CssSelector\Parser\Token; use Symfony\Component\CssSelector\Parser\TokenStream; @@ -53,7 +54,7 @@ public function testGetNextIdentifier() public function testFailToGetNextIdentifier() { - $this->expectException(\Symfony\Component\CssSelector\Exception\SyntaxErrorException::class); + $this->expectException(SyntaxErrorException::class); $stream = new TokenStream(); $stream->push(new Token(Token::TYPE_DELIMITER, '.', 2)); @@ -73,7 +74,7 @@ public function testGetNextIdentifierOrStar() public function testFailToGetNextIdentifierOrStar() { - $this->expectException(\Symfony\Component\CssSelector\Exception\SyntaxErrorException::class); + $this->expectException(SyntaxErrorException::class); $stream = new TokenStream(); $stream->push(new Token(Token::TYPE_DELIMITER, '.', 2)); diff --git a/src/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.php b/src/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.php index 57fb19fead3a..f04d8cdd3e5d 100644 --- a/src/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.php +++ b/src/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\CssSelector\Tests\XPath; use PHPUnit\Framework\TestCase; +use Symfony\Component\CssSelector\Exception\ExpressionErrorException; use Symfony\Component\CssSelector\Node\ElementNode; use Symfony\Component\CssSelector\Node\FunctionNode; use Symfony\Component\CssSelector\Parser\Parser; @@ -37,7 +38,7 @@ public function testCssToXPath($css, $xpath) public function testCssToXPathPseudoElement() { - $this->expectException(\Symfony\Component\CssSelector\Exception\ExpressionErrorException::class); + $this->expectException(ExpressionErrorException::class); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $translator->cssToXPath('e::first-line'); @@ -45,7 +46,7 @@ public function testCssToXPathPseudoElement() public function testGetExtensionNotExistsExtension() { - $this->expectException(\Symfony\Component\CssSelector\Exception\ExpressionErrorException::class); + $this->expectException(ExpressionErrorException::class); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $translator->getExtension('fake'); @@ -53,7 +54,7 @@ public function testGetExtensionNotExistsExtension() public function testAddCombinationNotExistsExtension() { - $this->expectException(\Symfony\Component\CssSelector\Exception\ExpressionErrorException::class); + $this->expectException(ExpressionErrorException::class); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $parser = new Parser(); @@ -64,7 +65,7 @@ public function testAddCombinationNotExistsExtension() public function testAddFunctionNotExistsFunction() { - $this->expectException(\Symfony\Component\CssSelector\Exception\ExpressionErrorException::class); + $this->expectException(ExpressionErrorException::class); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $xpath = new XPathExpr(); @@ -74,7 +75,7 @@ public function testAddFunctionNotExistsFunction() public function testAddPseudoClassNotExistsClass() { - $this->expectException(\Symfony\Component\CssSelector\Exception\ExpressionErrorException::class); + $this->expectException(ExpressionErrorException::class); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $xpath = new XPathExpr(); @@ -83,7 +84,7 @@ public function testAddPseudoClassNotExistsClass() public function testAddAttributeMatchingClassNotExistsClass() { - $this->expectException(\Symfony\Component\CssSelector\Exception\ExpressionErrorException::class); + $this->expectException(ExpressionErrorException::class); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $xpath = new XPathExpr(); diff --git a/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php b/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php index dc9617d0fa05..0e91ef0331c1 100644 --- a/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php +++ b/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Debug\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\Debug\Tests\Fixtures\ExtendsDeprecatedParent; use Symfony\Component\Debug\DebugClassLoader; /** @@ -179,7 +180,7 @@ public function testDeprecatedSuperInSameNamespace() $e = error_reporting(0); trigger_error('', E_USER_NOTICE); - class_exists(\Symfony\Bridge\Debug\Tests\Fixtures\ExtendsDeprecatedParent::class, true); + class_exists(ExtendsDeprecatedParent::class, true); error_reporting($e); restore_error_handler(); diff --git a/src/Symfony/Component/Debug/Tests/ErrorHandlerTest.php b/src/Symfony/Component/Debug/Tests/ErrorHandlerTest.php index 6c2b31a5118a..1fa2ca18626f 100644 --- a/src/Symfony/Component/Debug/Tests/ErrorHandlerTest.php +++ b/src/Symfony/Component/Debug/Tests/ErrorHandlerTest.php @@ -12,10 +12,12 @@ namespace Symfony\Component\Debug\Tests; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; use Psr\Log\NullLogger; use Symfony\Component\Debug\BufferingLogger; use Symfony\Component\Debug\ErrorHandler; +use Symfony\Component\Debug\Exception\ClassNotFoundException; use Symfony\Component\Debug\Exception\SilencedErrorContext; use Symfony\Component\Debug\Tests\Fixtures\ErrorHandlerThatUsesThePreviousOne; use Symfony\Component\Debug\Tests\Fixtures\LoggerThatSetAnErrorHandler; @@ -72,7 +74,7 @@ public function testRegister() public function testErrorGetLast() { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $handler = ErrorHandler::register(); $handler->setDefaultLogger($logger); $handler->screamAt(\E_ALL); @@ -150,7 +152,7 @@ public function testConstruct() public function testDefaultLogger() { try { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $handler = ErrorHandler::register(); $handler->setDefaultLogger($logger, \E_NOTICE); @@ -225,7 +227,7 @@ public function testHandleError() restore_error_handler(); restore_exception_handler(); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $warnArgCheck = function ($logLevel, $message, $context) { $this->assertEquals('info', $logLevel); @@ -250,7 +252,7 @@ public function testHandleError() restore_error_handler(); restore_exception_handler(); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $line = null; $logArgCheck = function ($level, $message, $context) use (&$line) { @@ -355,7 +357,7 @@ public function testHandleDeprecation() $this->assertSame('User Deprecated: Foo deprecation', $exception->getMessage()); }; - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $logger ->expects($this->once()) ->method('log') @@ -370,7 +372,7 @@ public function testHandleDeprecation() public function testHandleException() { try { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $handler = ErrorHandler::register(); $exception = new \Exception('foo'); @@ -450,7 +452,7 @@ public function testBootstrappingLogger() $bootLogger->log(LogLevel::WARNING, 'Foo message', ['exception' => $exception]); - $mockLogger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $mockLogger = $this->createMock(LoggerInterface::class); $mockLogger->expects($this->once()) ->method('log') ->with(LogLevel::WARNING, 'Foo message', ['exception' => $exception]); @@ -465,7 +467,7 @@ public function testSettingLoggerWhenExceptionIsBuffered() $exception = new \Exception('Foo message'); - $mockLogger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $mockLogger = $this->createMock(LoggerInterface::class); $mockLogger->expects($this->once()) ->method('log') ->with(LogLevel::CRITICAL, 'Uncaught Exception: Foo message', ['exception' => $exception]); @@ -480,7 +482,7 @@ public function testSettingLoggerWhenExceptionIsBuffered() public function testHandleFatalError() { try { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $handler = ErrorHandler::register(); $error = [ @@ -527,7 +529,7 @@ public function testHandleErrorException() $handler->handleException($exception); - $this->assertInstanceOf(\Symfony\Component\Debug\Exception\ClassNotFoundException::class, $args[0]); + $this->assertInstanceOf(ClassNotFoundException::class, $args[0]); $this->assertStringStartsWith("Attempted to load class \"IReallyReallyDoNotExistAnywhereInTheRepositoryISwear\" from the global namespace.\nDid you forget a \"use\" statement", $args[0]->getMessage()); } diff --git a/src/Symfony/Component/Debug/Tests/FatalErrorHandler/ClassNotFoundFatalErrorHandlerTest.php b/src/Symfony/Component/Debug/Tests/FatalErrorHandler/ClassNotFoundFatalErrorHandlerTest.php index 592a1ebea580..7e2406dda95f 100644 --- a/src/Symfony/Component/Debug/Tests/FatalErrorHandler/ClassNotFoundFatalErrorHandlerTest.php +++ b/src/Symfony/Component/Debug/Tests/FatalErrorHandler/ClassNotFoundFatalErrorHandlerTest.php @@ -14,6 +14,7 @@ use Composer\Autoload\ClassLoader as ComposerClassLoader; use PHPUnit\Framework\TestCase; use Symfony\Component\Debug\DebugClassLoader; +use Symfony\Component\Debug\Exception\ClassNotFoundException; use Symfony\Component\Debug\Exception\FatalErrorException; use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler; @@ -67,7 +68,7 @@ public function testHandleClassNotFound($error, $translatedMessage, $autoloader array_map('spl_autoload_register', $autoloaders); } - $this->assertInstanceOf(\Symfony\Component\Debug\Exception\ClassNotFoundException::class, $exception); + $this->assertInstanceOf(ClassNotFoundException::class, $exception); $this->assertMatchesRegularExpression($translatedMessage, $exception->getMessage()); $this->assertSame($error['type'], $exception->getSeverity()); $this->assertSame($error['file'], $exception->getFile()); @@ -218,6 +219,6 @@ public function testCannotRedeclareClass() $handler = new ClassNotFoundFatalErrorHandler(); $exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line'])); - $this->assertInstanceOf(\Symfony\Component\Debug\Exception\ClassNotFoundException::class, $exception); + $this->assertInstanceOf(ClassNotFoundException::class, $exception); } } diff --git a/src/Symfony/Component/Debug/Tests/FatalErrorHandler/UndefinedFunctionFatalErrorHandlerTest.php b/src/Symfony/Component/Debug/Tests/FatalErrorHandler/UndefinedFunctionFatalErrorHandlerTest.php index e46b4293dea2..7406d7f345cf 100644 --- a/src/Symfony/Component/Debug/Tests/FatalErrorHandler/UndefinedFunctionFatalErrorHandlerTest.php +++ b/src/Symfony/Component/Debug/Tests/FatalErrorHandler/UndefinedFunctionFatalErrorHandlerTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Debug\Exception\FatalErrorException; +use Symfony\Component\Debug\Exception\UndefinedFunctionException; use Symfony\Component\Debug\FatalErrorHandler\UndefinedFunctionFatalErrorHandler; /** @@ -28,7 +29,7 @@ public function testUndefinedFunction($error, $translatedMessage) $handler = new UndefinedFunctionFatalErrorHandler(); $exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line'])); - $this->assertInstanceOf(\Symfony\Component\Debug\Exception\UndefinedFunctionException::class, $exception); + $this->assertInstanceOf(UndefinedFunctionException::class, $exception); // class names are case insensitive and PHP do not return the same $this->assertSame(strtolower($translatedMessage), strtolower($exception->getMessage())); $this->assertSame($error['type'], $exception->getSeverity()); diff --git a/src/Symfony/Component/Debug/Tests/FatalErrorHandler/UndefinedMethodFatalErrorHandlerTest.php b/src/Symfony/Component/Debug/Tests/FatalErrorHandler/UndefinedMethodFatalErrorHandlerTest.php index d1b8018b4669..55f2f62880b2 100644 --- a/src/Symfony/Component/Debug/Tests/FatalErrorHandler/UndefinedMethodFatalErrorHandlerTest.php +++ b/src/Symfony/Component/Debug/Tests/FatalErrorHandler/UndefinedMethodFatalErrorHandlerTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Debug\Exception\FatalErrorException; +use Symfony\Component\Debug\Exception\UndefinedMethodException; use Symfony\Component\Debug\FatalErrorHandler\UndefinedMethodFatalErrorHandler; /** @@ -28,7 +29,7 @@ public function testUndefinedMethod($error, $translatedMessage) $handler = new UndefinedMethodFatalErrorHandler(); $exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line'])); - $this->assertInstanceOf(\Symfony\Component\Debug\Exception\UndefinedMethodException::class, $exception); + $this->assertInstanceOf(UndefinedMethodException::class, $exception); $this->assertSame($translatedMessage, $exception->getMessage()); $this->assertSame($error['type'], $exception->getSeverity()); $this->assertSame($error['file'], $exception->getFile()); diff --git a/src/Symfony/Component/DependencyInjection/Tests/AliasTest.php b/src/Symfony/Component/DependencyInjection/Tests/AliasTest.php index 12e30b9b80ec..19c152e7afae 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/AliasTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/AliasTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Alias; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; class AliasTest extends TestCase { @@ -90,7 +91,7 @@ public function testCanOverrideDeprecation() */ public function testCannotDeprecateWithAnInvalidTemplate($message) { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $def = new Alias('foo'); $def->setDeprecated(true, $message); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php b/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php index 35f25c0714f5..9cf2ecb7234e 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\ChildDefinition; +use Symfony\Component\DependencyInjection\Exception\BadMethodCallException; class ChildDefinitionTest extends TestCase { @@ -129,14 +130,14 @@ public function testGetArgumentShouldCheckBounds() public function testCannotCallSetAutoconfigured() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\BadMethodCallException::class); + $this->expectException(BadMethodCallException::class); $def = new ChildDefinition('foo'); $def->setAutoconfigured(true); } public function testCannotCallSetInstanceofConditionals() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\BadMethodCallException::class); + $this->expectException(BadMethodCallException::class); $def = new ChildDefinition('foo'); $def->setInstanceofConditionals(['Foo' => new ChildDefinition('')]); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php index 7b13d72ddbb4..26a0ed155502 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php @@ -14,12 +14,14 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Compiler\AutoAliasServicePass; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException; class AutoAliasServicePassTest extends TestCase { public function testProcessWithMissingParameter() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException::class); + $this->expectException(ParameterNotFoundException::class); $container = new ContainerBuilder(); $container->register('example') @@ -31,7 +33,7 @@ public function testProcessWithMissingParameter() public function testProcessWithMissingFormat() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $container = new ContainerBuilder(); $container->register('example') diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckArgumentsValidityPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckArgumentsValidityPassTest.php index c8b17acb50ad..1253abb37ff8 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckArgumentsValidityPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckArgumentsValidityPassTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Compiler\CheckArgumentsValidityPass; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; /** * @author Kévin Dunglas @@ -45,7 +46,7 @@ public function testProcess() */ public function testException(array $arguments, array $methodCalls) { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $container = new ContainerBuilder(); $definition = $container->register('foo'); $definition->setArguments($arguments); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.php index 60f635c0eb8a..960c6331e4f9 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.php @@ -17,13 +17,14 @@ use Symfony\Component\DependencyInjection\Compiler\CheckCircularReferencesPass; use Symfony\Component\DependencyInjection\Compiler\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\Reference; class CheckCircularReferencesPassTest extends TestCase { public function testProcess() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException::class); + $this->expectException(ServiceCircularReferenceException::class); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('a')); @@ -33,7 +34,7 @@ public function testProcess() public function testProcessWithAliases() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException::class); + $this->expectException(ServiceCircularReferenceException::class); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->setAlias('b', 'c'); @@ -44,7 +45,7 @@ public function testProcessWithAliases() public function testProcessWithFactory() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException::class); + $this->expectException(ServiceCircularReferenceException::class); $container = new ContainerBuilder(); $container @@ -60,7 +61,7 @@ public function testProcessWithFactory() public function testProcessDetectsIndirectCircularReference() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException::class); + $this->expectException(ServiceCircularReferenceException::class); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('c')); @@ -71,7 +72,7 @@ public function testProcessDetectsIndirectCircularReference() public function testProcessDetectsIndirectCircularReferenceWithFactory() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException::class); + $this->expectException(ServiceCircularReferenceException::class); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); @@ -87,7 +88,7 @@ public function testProcessDetectsIndirectCircularReferenceWithFactory() public function testDeepCircularReference() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException::class); + $this->expectException(ServiceCircularReferenceException::class); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('c')); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.php index 8ac217a98939..ed1e300ce053 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Compiler\CheckDefinitionValidityPass; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\EnvParameterException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; class CheckDefinitionValidityPassTest extends TestCase @@ -86,7 +87,7 @@ public function testInvalidTags() public function testDynamicPublicServiceName() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\EnvParameterException::class); + $this->expectException(EnvParameterException::class); $container = new ContainerBuilder(); $env = $container->getParameterBag()->get('env(BAR)'); $container->register("foo.$env", 'class')->setPublic(true); @@ -96,7 +97,7 @@ public function testDynamicPublicServiceName() public function testDynamicPublicAliasName() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\EnvParameterException::class); + $this->expectException(EnvParameterException::class); $container = new ContainerBuilder(); $env = $container->getParameterBag()->get('env(BAR)'); $container->setAlias("foo.$env", 'class')->setPublic(true); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php index e00ae5bf1642..2692cd05ccc1 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php @@ -19,6 +19,7 @@ use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\Reference; class CheckExceptionOnInvalidReferenceBehaviorPassTest extends TestCase @@ -40,7 +41,7 @@ public function testProcess() public function testProcessThrowsExceptionOnInvalidReference() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class); + $this->expectException(ServiceNotFoundException::class); $container = new ContainerBuilder(); $container @@ -53,7 +54,7 @@ public function testProcessThrowsExceptionOnInvalidReference() public function testProcessThrowsExceptionOnInvalidReferenceFromInlinedDefinition() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class); + $this->expectException(ServiceNotFoundException::class); $container = new ContainerBuilder(); $def = new Definition(); @@ -83,7 +84,7 @@ public function testProcessDefinitionWithBindings() public function testWithErroredServiceLocator() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class); + $this->expectException(ServiceNotFoundException::class); $this->expectExceptionMessage('The service "foo" in the container provided to "bar" has a dependency on a non-existent service "baz".'); $container = new ContainerBuilder(); @@ -96,7 +97,7 @@ public function testWithErroredServiceLocator() public function testWithErroredHiddenService() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class); + $this->expectException(ServiceNotFoundException::class); $this->expectExceptionMessage('The service "bar" has a dependency on a non-existent service "foo".'); $container = new ContainerBuilder(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckTypeDeclarationsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckTypeDeclarationsPassTest.php index 5d625308a59e..6dc382a4542a 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckTypeDeclarationsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckTypeDeclarationsPassTest.php @@ -18,6 +18,8 @@ use Symfony\Component\DependencyInjection\Compiler\ResolveParameterPlaceHoldersPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Exception\InvalidParameterTypeException; use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Tests\Fixtures\CheckTypeDeclarationsPass\Bar; @@ -40,7 +42,7 @@ class CheckTypeDeclarationsPassTest extends TestCase { public function testProcessThrowsExceptionOnInvalidTypesConstructorArguments() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Bar::__construct()" accepts "stdClass", "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Foo" passed.'); $container = new ContainerBuilder(); @@ -54,7 +56,7 @@ public function testProcessThrowsExceptionOnInvalidTypesConstructorArguments() public function testProcessThrowsExceptionOnInvalidTypesMethodCallArguments() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\BarMethodCall::setFoo()" accepts "stdClass", "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Foo" passed.'); $container = new ContainerBuilder(); @@ -68,7 +70,7 @@ public function testProcessThrowsExceptionOnInvalidTypesMethodCallArguments() public function testProcessFailsWhenPassingNullToRequiredArgument() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Bar::__construct()" accepts "stdClass", "NULL" passed.'); $container = new ContainerBuilder(); @@ -81,7 +83,7 @@ public function testProcessFailsWhenPassingNullToRequiredArgument() public function testProcessThrowsExceptionWhenMissingArgumentsInConstructor() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Bar::__construct()" requires 1 arguments, 0 passed.'); $container = new ContainerBuilder(); @@ -118,7 +120,7 @@ public function testProcessRegisterWithClassName() public function testProcessThrowsExceptionWhenMissingArgumentsInMethodCall() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\BarMethodCall::setFoo()" requires 1 arguments, 0 passed.'); $container = new ContainerBuilder(); @@ -133,7 +135,7 @@ public function testProcessThrowsExceptionWhenMissingArgumentsInMethodCall() public function testProcessVariadicFails() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 2 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\BarMethodCall::setFoosVariadic()" accepts "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Foo", "stdClass" passed.'); $container = new ContainerBuilder(); @@ -152,7 +154,7 @@ public function testProcessVariadicFails() public function testProcessVariadicFailsOnPassingBadTypeOnAnotherArgument() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\BarMethodCall::setFoosVariadic()" accepts "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Foo", "stdClass" passed.'); $container = new ContainerBuilder(); @@ -216,7 +218,7 @@ public function testProcessSuccessWhenUsingOptionalArgumentWithGoodType() public function testProcessFailsWhenUsingOptionalArgumentWithBadType() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 2 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\BarMethodCall::setFoosOptional()" accepts "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Foo", "stdClass" passed.'); $container = new ContainerBuilder(); @@ -246,7 +248,7 @@ public function testProcessSuccessWhenPassingNullToOptional() public function testProcessSuccessWhenPassingNullToOptionalThatDoesNotAcceptNull() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\BarOptionalArgumentNotNull::__construct()" accepts "int", "NULL" passed.'); $container = new ContainerBuilder(); @@ -259,7 +261,7 @@ public function testProcessSuccessWhenPassingNullToOptionalThatDoesNotAcceptNull public function testProcessFailsWhenPassingBadTypeToOptional() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\BarOptionalArgument::__construct()" accepts "stdClass", "string" passed.'); $container = new ContainerBuilder(); @@ -289,7 +291,7 @@ public function testProcessSuccessScalarType() public function testProcessFailsOnPassingScalarTypeToConstructorTypedWithClass() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Bar::__construct()" accepts "stdClass", "integer" passed.'); $container = new ContainerBuilder(); @@ -302,7 +304,7 @@ public function testProcessFailsOnPassingScalarTypeToConstructorTypedWithClass() public function testProcessFailsOnPassingScalarTypeToMethodTypedWithClass() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\BarMethodCall::setFoo()" accepts "stdClass", "string" passed.'); $container = new ContainerBuilder(); @@ -317,7 +319,7 @@ public function testProcessFailsOnPassingScalarTypeToMethodTypedWithClass() public function testProcessFailsOnPassingClassToScalarTypedParameter() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\BarMethodCall::setScalars()" accepts "int", "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Foo" passed.'); $container = new ContainerBuilder(); @@ -377,7 +379,7 @@ public function testProcessSuccessWhenPassingArray() public function testProcessSuccessWhenPassingIntegerToArrayTypedParameter() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidParameterTypeException::class); + $this->expectException(InvalidParameterTypeException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\Component\DependencyInjection\Tests\Fixtures\CheckTypeDeclarationsPass\BarMethodCall::setArray()" accepts "array", "integer" passed.'); $container = new ContainerBuilder(); @@ -437,7 +439,7 @@ public function testProcessFactory() public function testProcessFactoryFailsOnInvalidParameterType() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Foo::createBarArguments()" accepts "stdClass", "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Foo" passed.'); $container = new ContainerBuilder(); @@ -455,7 +457,7 @@ public function testProcessFactoryFailsOnInvalidParameterType() public function testProcessFactoryFailsOnInvalidParameterTypeOptional() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar": argument 2 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Foo::createBarArguments()" accepts "stdClass", "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Foo" passed.'); $container = new ContainerBuilder(); @@ -601,7 +603,7 @@ public function testProcessDoesNotThrowsExceptionOnValidTypes() public function testProcessThrowsOnIterableTypeWhenScalarPassed() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "bar_call": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\BarMethodCall::setIterable()" accepts "iterable", "integer" passed.'); $container = new ContainerBuilder(); @@ -645,7 +647,7 @@ public function testProcessSuccessWhenExpressionReturnsObject() public function testProcessHandleMixedEnvPlaceholder() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "foobar": argument 1 of "Symfony\Component\DependencyInjection\Tests\Fixtures\CheckTypeDeclarationsPass\BarMethodCall::setArray()" accepts "array", "string" passed.'); $container = new ContainerBuilder(new EnvPlaceholderParameterBag([ @@ -661,7 +663,7 @@ public function testProcessHandleMixedEnvPlaceholder() public function testProcessHandleMultipleEnvPlaceholder() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "foobar": argument 1 of "Symfony\Component\DependencyInjection\Tests\Fixtures\CheckTypeDeclarationsPass\BarMethodCall::setArray()" accepts "array", "string" passed.'); $container = new ContainerBuilder(new EnvPlaceholderParameterBag([ @@ -877,7 +879,7 @@ public function testUnionTypeFailsWithReference() $container->register('union', UnionConstructor::class) ->setArguments([new Reference('waldo')]); - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "union": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\UnionConstructor::__construct()" accepts "Symfony\Component\DependencyInjection\Tests\Fixtures\CheckTypeDeclarationsPass\Foo|int", "Symfony\Component\DependencyInjection\Tests\Fixtures\CheckTypeDeclarationsPass\Waldo" passed.'); (new CheckTypeDeclarationsPass(true))->process($container); @@ -893,7 +895,7 @@ public function testUnionTypeFailsWithBuiltin() $container->register('union', UnionConstructor::class) ->setArguments([[1, 2, 3]]); - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "union": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\UnionConstructor::__construct()" accepts "Symfony\Component\DependencyInjection\Tests\Fixtures\CheckTypeDeclarationsPass\Foo|int", "array" passed.'); (new CheckTypeDeclarationsPass(true))->process($container); @@ -911,7 +913,7 @@ public function testUnionTypeWithFalseFailsWithReference() ->setFactory([UnionConstructor::class, 'create']) ->setArguments([new Reference('waldo')]); - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "union": argument 1 of "Symfony\Component\DependencyInjection\Tests\Fixtures\CheckTypeDeclarationsPass\UnionConstructor::create()" accepts "array|false", "Symfony\Component\DependencyInjection\Tests\Fixtures\CheckTypeDeclarationsPass\Waldo" passed.'); (new CheckTypeDeclarationsPass(true))->process($container); @@ -929,7 +931,7 @@ public function testUnionTypeWithFalseFailsWithTrue() ->setFactory([UnionConstructor::class, 'create']) ->setArguments([true]); - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "union": argument 1 of "Symfony\Component\DependencyInjection\Tests\Fixtures\CheckTypeDeclarationsPass\UnionConstructor::create()" accepts "array|false", "boolean" passed.'); (new CheckTypeDeclarationsPass(true))->process($container); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/DecoratorServicePassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/DecoratorServicePassTest.php index 2bf822f2e702..ce9a2cfafeeb 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/DecoratorServicePassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/DecoratorServicePassTest.php @@ -16,6 +16,7 @@ use Symfony\Component\DependencyInjection\Compiler\DecoratorServicePass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; class DecoratorServicePassTest extends TestCase { @@ -153,7 +154,7 @@ public function testProcessWithInvalidDecorated() ->setDecoratedService('unknown_service') ; - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class); + $this->expectException(ServiceNotFoundException::class); $this->process($container); } @@ -177,7 +178,7 @@ public function testProcessWithInvalidDecoratedAndWrongBehavior() ->setDecoratedService('unknown_decorated', null, 0, 12) ; - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class); + $this->expectException(ServiceNotFoundException::class); $this->process($container); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/DefinitionErrorExceptionPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/DefinitionErrorExceptionPassTest.php index f17717f1dfa2..b22b934dd80c 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/DefinitionErrorExceptionPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/DefinitionErrorExceptionPassTest.php @@ -15,12 +15,13 @@ use Symfony\Component\DependencyInjection\Compiler\DefinitionErrorExceptionPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; class DefinitionErrorExceptionPassTest extends TestCase { public function testThrowsException() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Things went wrong!'); $container = new ContainerBuilder(); $def = new Definition(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php index 9c22b3a47327..4f01d33c4923 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php @@ -18,6 +18,7 @@ use Symfony\Component\DependencyInjection\Compiler\InlineServiceDefinitionsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\Reference; class InlineServiceDefinitionsPassTest extends TestCase @@ -114,7 +115,7 @@ public function testProcessDoesNotInlineMixedServicesLoop() public function testProcessThrowsOnNonSharedLoops() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException::class); + $this->expectException(ServiceCircularReferenceException::class); $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> foo -> bar".'); $container = new ContainerBuilder(); $container diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/MergeExtensionConfigurationPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/MergeExtensionConfigurationPassTest.php index c9a4aa72fae0..f695c428712f 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/MergeExtensionConfigurationPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/MergeExtensionConfigurationPassTest.php @@ -19,8 +19,11 @@ use Symfony\Component\DependencyInjection\Compiler\MergeExtensionConfigurationContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\MergeExtensionConfigurationPass; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Extension\Extension; +use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; +use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; class MergeExtensionConfigurationPassTest extends TestCase { @@ -28,7 +31,7 @@ public function testExpressionLanguageProviderForwarding() { $tmpProviders = []; - $extension = $this->getMockBuilder(\Symfony\Component\DependencyInjection\Extension\ExtensionInterface::class)->getMock(); + $extension = $this->createMock(ExtensionInterface::class); $extension->expects($this->any()) ->method('getXsdValidationBasePath') ->willReturn(false); @@ -44,7 +47,7 @@ public function testExpressionLanguageProviderForwarding() $tmpProviders = $container->getExpressionLanguageProviders(); }); - $provider = $this->getMockBuilder(\Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface::class)->getMock(); + $provider = $this->createMock(ExpressionFunctionProviderInterface::class); $container = new ContainerBuilder(new ParameterBag()); $container->registerExtension($extension); $container->prependExtensionConfig('foo', ['bar' => true]); @@ -105,7 +108,7 @@ public function testOverriddenEnvsAreMerged() public function testProcessedEnvsAreIncompatibleWithResolve() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Using a cast in "env(int:FOO)" is incompatible with resolution at compile time in "Symfony\Component\DependencyInjection\Tests\Compiler\BarExtension". The logic in the extension should be moved to a compiler pass, or an env parameter with no cast should be used instead.'); $container = new ContainerBuilder(); $container->registerExtension(new BarExtension()); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/PassConfigTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/PassConfigTest.php index f8556d3e06f0..8001c5401028 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/PassConfigTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/PassConfigTest.php @@ -25,10 +25,10 @@ public function testPassOrdering() $config = new PassConfig(); $config->setBeforeOptimizationPasses([]); - $pass1 = $this->getMockBuilder(CompilerPassInterface::class)->getMock(); + $pass1 = $this->createMock(CompilerPassInterface::class); $config->addPass($pass1, PassConfig::TYPE_BEFORE_OPTIMIZATION, 10); - $pass2 = $this->getMockBuilder(CompilerPassInterface::class)->getMock(); + $pass2 = $this->createMock(CompilerPassInterface::class); $config->addPass($pass2, PassConfig::TYPE_BEFORE_OPTIMIZATION, 30); $passes = $config->getBeforeOptimizationPasses(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php index 4d513d2ee0c2..5e83f13b5dd2 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php @@ -15,6 +15,7 @@ use Symfony\Component\DependencyInjection\Compiler\RegisterEnvVarProcessorsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\EnvVarProcessorInterface; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; class RegisterEnvVarProcessorsPassTest extends TestCase { @@ -62,7 +63,7 @@ public function testNoProcessor() public function testBadProcessor() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid type "foo" returned by "Symfony\Component\DependencyInjection\Tests\Compiler\BadProcessor::getProvidedTypes()", expected one of "array", "bool", "float", "int", "string".'); $container = new ContainerBuilder(); $container->register('foo', BadProcessor::class)->addTag('container.env_var_processor'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterServiceSubscribersPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterServiceSubscribersPassTest.php index 8846f602c752..beb1fb35d5ec 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterServiceSubscribersPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterServiceSubscribersPassTest.php @@ -20,6 +20,7 @@ use Symfony\Component\DependencyInjection\Compiler\ResolveServiceSubscribersPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ServiceLocator; use Symfony\Component\DependencyInjection\ServiceSubscriberInterface; @@ -39,7 +40,7 @@ class RegisterServiceSubscribersPassTest extends TestCase { public function testInvalidClass() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Service "foo" must implement interface "Symfony\Contracts\Service\ServiceSubscriberInterface".'); $container = new ContainerBuilder(); @@ -53,7 +54,7 @@ public function testInvalidClass() public function testInvalidAttributes() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "container.service_subscriber" tag accepts only the "key" and "id" attributes, "bar" given for service "foo".'); $container = new ContainerBuilder(); @@ -127,7 +128,7 @@ public function testWithAttributes() public function testExtraServiceSubscriber() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Service key "test" does not exist in the map returned by "Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber::getSubscribedServices()" for service "foo_service".'); $container = new ContainerBuilder(); $container->register('foo_service', TestServiceSubscriber::class) diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveBindingsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveBindingsPassTest.php index e6d8344bab09..199961a10d6f 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveBindingsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveBindingsPassTest.php @@ -21,6 +21,7 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass; use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy; @@ -134,7 +135,7 @@ public function testScalarSetter() public function testWithNonExistingSetterAndBinding() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "setLogger()" does not exist.'); $container = new ContainerBuilder(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveChildDefinitionsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveChildDefinitionsPassTest.php index 1216e59a8b28..7dea34d75c8b 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveChildDefinitionsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveChildDefinitionsPassTest.php @@ -15,6 +15,7 @@ use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; class ResolveChildDefinitionsPassTest extends TestCase { @@ -399,7 +400,7 @@ protected function process(ContainerBuilder $container) public function testProcessDetectsChildDefinitionIndirectCircularReference() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException::class); + $this->expectException(ServiceCircularReferenceException::class); $this->expectExceptionMessageMatches('/^Circular reference detected for service "c", path: "c -> b -> a -> c"./'); $container = new ContainerBuilder(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveClassPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveClassPassTest.php index 0f56bfeac8f8..69b9a1c2d384 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveClassPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveClassPassTest.php @@ -15,6 +15,7 @@ use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\Compiler\ResolveClassPass; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass; class ResolveClassPassTest extends TestCase @@ -84,7 +85,7 @@ public function testClassFoundChildDefinition() public function testAmbiguousChildDefinition() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Service definition "App\Foo\Child" has a parent but no class, and its name looks like a FQCN. Either the class is missing or you want to inherit it from the parent service. To resolve this ambiguity, please rename this service to a non-FQCN (e.g. using dots), or create the missing class.'); $container = new ContainerBuilder(); $container->register('App\Foo', null); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveFactoryClassPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveFactoryClassPassTest.php index 2c3fd5917385..6b69e0bf2151 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveFactoryClassPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveFactoryClassPassTest.php @@ -15,6 +15,7 @@ use Symfony\Component\DependencyInjection\Compiler\ResolveFactoryClassPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Reference; class ResolveFactoryClassPassTest extends TestCase @@ -73,7 +74,7 @@ public function testIgnoresFulfilledFactories($factory) public function testNotAnyClassThrowsException() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The "factory" service is defined to be created by a factory, but is missing the factory class. Did you forget to define the factory or service class?'); $container = new ContainerBuilder(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php index 2f749362d26b..d750ce69583d 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php @@ -19,6 +19,8 @@ use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass; use Symfony\Component\DependencyInjection\Compiler\ResolveInstanceofConditionalsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Reference; use Symfony\Contracts\Service\ResetInterface; use Symfony\Contracts\Service\ServiceSubscriberInterface; @@ -179,7 +181,7 @@ public function testProcessDoesNotUseAutoconfiguredInstanceofIfNotEnabled() public function testBadInterfaceThrowsException() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('"App\FakeInterface" is set as an "instanceof" conditional, but it does not exist.'); $container = new ContainerBuilder(); $def = $container->register('normal_service', self::class); @@ -236,7 +238,7 @@ public function testProcessForAutoconfiguredCalls() public function testProcessThrowsExceptionForArguments() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageMatches('/Autoconfigured instanceof for type "PHPUnit[\\\\_]Framework[\\\\_]TestCase" defines arguments but these are not supported and should be removed\./'); $container = new ContainerBuilder(); $container->registerForAutoconfiguration(parent::class) diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveNamedArgumentsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveNamedArgumentsPassTest.php index 61e5c72eec47..4e9973bb30e9 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveNamedArgumentsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveNamedArgumentsPassTest.php @@ -15,6 +15,8 @@ use Psr\Container\ContainerInterface; use Symfony\Component\DependencyInjection\Compiler\ResolveNamedArgumentsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass; use Symfony\Component\DependencyInjection\Tests\Fixtures\FactoryDummyWithoutReturnTypes; @@ -64,7 +66,7 @@ public function testWithFactory() public function testClassNull() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $container = new ContainerBuilder(); $definition = $container->register(NamedArgumentsDummy::class); @@ -76,7 +78,7 @@ public function testClassNull() public function testClassNotExist() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $container = new ContainerBuilder(); $definition = $container->register(NotExist::class, NotExist::class); @@ -88,7 +90,7 @@ public function testClassNotExist() public function testClassNoConstructor() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $container = new ContainerBuilder(); $definition = $container->register(NoConstructor::class, NoConstructor::class); @@ -100,7 +102,7 @@ public function testClassNoConstructor() public function testArgumentNotFound() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "__construct()" has no argument named "$notFound". Check your service definition.'); $container = new ContainerBuilder(); @@ -113,7 +115,7 @@ public function testArgumentNotFound() public function testCorrectMethodReportedInException() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\TestDefinition1": method "Symfony\Component\DependencyInjection\Tests\Fixtures\FactoryDummyWithoutReturnTypes::createTestDefinition1()" has no argument named "$notFound". Check your service definition.'); $container = new ContainerBuilder(); @@ -142,7 +144,7 @@ public function testTypedArgument() public function testTypedArgumentWithMissingDollar() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": did you forget to add the "$" prefix to argument "apiKey"?'); $container = new ContainerBuilder(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveReferencesToAliasesPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveReferencesToAliasesPassTest.php index 86e3a7ae4c12..3c4da3b643dd 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveReferencesToAliasesPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveReferencesToAliasesPassTest.php @@ -16,6 +16,7 @@ use Symfony\Component\DependencyInjection\Compiler\ResolveReferencesToAliasesPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\Reference; class ResolveReferencesToAliasesPassTest extends TestCase @@ -53,7 +54,7 @@ public function testProcessRecursively() public function testAliasCircularReference() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException::class); + $this->expectException(ServiceCircularReferenceException::class); $container = new ContainerBuilder(); $container->setAlias('bar', 'foo'); $container->setAlias('foo', 'bar'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ServiceLocatorTagPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ServiceLocatorTagPassTest.php index 2e9cc686c559..25063d35ff3b 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ServiceLocatorTagPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ServiceLocatorTagPassTest.php @@ -15,6 +15,7 @@ use Symfony\Component\DependencyInjection\Argument\BoundArgument; use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ServiceLocator; use Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition; @@ -27,7 +28,7 @@ class ServiceLocatorTagPassTest extends TestCase { public function testNoServices() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "foo": an array of references is expected as first argument when the "container.service_locator" tag is set.'); $container = new ContainerBuilder(); @@ -40,7 +41,7 @@ public function testNoServices() public function testInvalidServices() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid definition for service "foo": an array of references is expected as first argument when the "container.service_locator" tag is set, "string" found for key "0".'); $container = new ContainerBuilder(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php index 0a28a4363d85..dd88c71227c5 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php @@ -14,6 +14,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; +use Symfony\Component\Config\Definition\Exception\InvalidTypeException; use Symfony\Component\Config\Definition\Exception\TreeWithoutRootNodeException; use Symfony\Component\DependencyInjection\Compiler\MergeExtensionConfigurationPass; use Symfony\Component\DependencyInjection\Compiler\RegisterEnvVarProcessorsPass; @@ -44,7 +46,7 @@ public function testEnvsAreValidatedInConfig() public function testDefaultEnvIsValidatedInConfig() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('Invalid configuration for path "env_extension.string_node": "fail" is not a valid string'); $container = new ContainerBuilder(); $container->setParameter('env(STRING)', 'fail'); @@ -76,7 +78,7 @@ public function testDefaultEnvWithoutPrefixIsValidatedInConfig() public function testEnvsAreValidatedInConfigWithInvalidPlaceholder() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidTypeException::class); + $this->expectException(InvalidTypeException::class); $this->expectExceptionMessage('Invalid type for path "env_extension.bool_node". Expected "bool", but got one of "bool", "int", "float", "string", "array".'); $container = new ContainerBuilder(); $container->registerExtension($ext = new EnvExtension()); @@ -91,7 +93,7 @@ public function testEnvsAreValidatedInConfigWithInvalidPlaceholder() public function testInvalidEnvInConfig() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidTypeException::class); + $this->expectException(InvalidTypeException::class); $this->expectExceptionMessage('Invalid type for path "env_extension.int_node". Expected "int", but got "array".'); $container = new ContainerBuilder(); $container->registerExtension(new EnvExtension()); @@ -104,7 +106,7 @@ public function testInvalidEnvInConfig() public function testNulledEnvInConfig() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidTypeException::class); + $this->expectException(InvalidTypeException::class); $this->expectExceptionMessageMatches('/^Invalid type for path "env_extension\.int_node"\. Expected "?int"?, but got (NULL|"null")\.$/'); $container = new ContainerBuilder(); $container->setParameter('env(NULLED)', null); @@ -156,7 +158,7 @@ public function testConcatenatedEnvInConfig() public function testEnvIsIncompatibleWithEnumNode() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('A dynamic value is not compatible with a "Symfony\Component\Config\Definition\EnumNode" node type at path "env_extension.enum_node".'); $container = new ContainerBuilder(); $container->registerExtension(new EnvExtension()); @@ -169,7 +171,7 @@ public function testEnvIsIncompatibleWithEnumNode() public function testEnvIsIncompatibleWithArrayNode() { - $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('A dynamic value is not compatible with a "Symfony\Component\Config\Definition\ArrayNode" node type at path "env_extension.simple_array_node".'); $container = new ContainerBuilder(); $container->registerExtension(new EnvExtension()); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Config/ContainerParametersResourceCheckerTest.php b/src/Symfony/Component/DependencyInjection/Tests/Config/ContainerParametersResourceCheckerTest.php index 41ac029f2d69..08ff5c797e18 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Config/ContainerParametersResourceCheckerTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Config/ContainerParametersResourceCheckerTest.php @@ -32,7 +32,7 @@ class ContainerParametersResourceCheckerTest extends TestCase protected function setUp(): void { $this->resource = new ContainerParametersResource(['locales' => ['fr', 'en'], 'default_locale' => 'fr']); - $this->container = $this->getMockBuilder(ContainerInterface::class)->getMock(); + $this->container = $this->createMock(ContainerInterface::class); $this->resourceChecker = new ContainerParametersResourceChecker($this->container); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php b/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php index 4de833ba8daa..8a3f22981870 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php @@ -26,12 +26,18 @@ use Symfony\Component\DependencyInjection\Argument\RewindableGenerator; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ChildDefinition; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Compiler\PassConfig; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Exception\EnvNotFoundException; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; +use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; +use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; use Symfony\Component\DependencyInjection\Loader\ClosureLoader; use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; @@ -148,7 +154,7 @@ public function testGetReturnsNullIfServiceDoesNotExistAndInvalidReferenceIsUsed public function testGetThrowsCircularReferenceExceptionIfServiceHasReferenceToItself() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException::class); + $this->expectException(ServiceCircularReferenceException::class); $builder = new ContainerBuilder(); $builder->register('baz', 'stdClass')->setArguments([new Reference('baz')]); $builder->get('baz'); @@ -200,7 +206,7 @@ public function testNonSharedServicesReturnsDifferentInstances() */ public function testBadAliasId($id) { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $builder = new ContainerBuilder(); $builder->setAlias($id, 'foo'); } @@ -210,7 +216,7 @@ public function testBadAliasId($id) */ public function testBadDefinitionId($id) { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $builder = new ContainerBuilder(); $builder->setDefinition($id, new Definition('Foo')); } @@ -375,8 +381,8 @@ public function testAddGetCompilerPass() $builder = new ContainerBuilder(); $builder->setResourceTracking(false); $defaultPasses = $builder->getCompiler()->getPassConfig()->getPasses(); - $builder->addCompilerPass($pass1 = $this->getMockBuilder(\Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface::class)->getMock(), PassConfig::TYPE_BEFORE_OPTIMIZATION, -5); - $builder->addCompilerPass($pass2 = $this->getMockBuilder(\Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface::class)->getMock(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 10); + $builder->addCompilerPass($pass1 = $this->createMock(CompilerPassInterface::class), PassConfig::TYPE_BEFORE_OPTIMIZATION, -5); + $builder->addCompilerPass($pass2 = $this->createMock(CompilerPassInterface::class), PassConfig::TYPE_BEFORE_OPTIMIZATION, 10); $passes = $builder->getCompiler()->getPassConfig()->getPasses(); $this->assertCount(\count($passes) - 2, $defaultPasses); @@ -632,7 +638,7 @@ public function testMerge() public function testMergeThrowsExceptionForDuplicateAutomaticInstanceofDefinitions() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('"AInterface" has already been autoconfigured and merge() does not support merging autoconfiguration for the same class/interface.'); $container = new ContainerBuilder(); $config = new ContainerBuilder(); @@ -750,7 +756,7 @@ public function testCompileWithArrayInStringResolveEnv() public function testCompileWithResolveMissingEnv() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\EnvNotFoundException::class); + $this->expectException(EnvNotFoundException::class); $this->expectExceptionMessage('Environment variable not found: "FOO".'); $container = new ContainerBuilder(); $container->setParameter('foo', '%env(FOO)%'); @@ -846,7 +852,7 @@ public function testEnvInId() public function testCircularDynamicEnv() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException::class); + $this->expectException(ParameterCircularReferenceException::class); $this->expectExceptionMessage('Circular reference detected for parameter "env(resolve:DUMMY_ENV_VAR)" ("env(resolve:DUMMY_ENV_VAR)" > "env(resolve:DUMMY_ENV_VAR)").'); putenv('DUMMY_ENV_VAR=some%foo%'); @@ -1046,7 +1052,7 @@ public function testExtension() public function testRegisteredButNotLoadedExtension() { - $extension = $this->getMockBuilder(\Symfony\Component\DependencyInjection\Extension\ExtensionInterface::class)->getMock(); + $extension = $this->createMock(ExtensionInterface::class); $extension->expects($this->once())->method('getAlias')->willReturn('project'); $extension->expects($this->never())->method('load'); @@ -1058,7 +1064,7 @@ public function testRegisteredButNotLoadedExtension() public function testRegisteredAndLoadedExtension() { - $extension = $this->getMockBuilder(\Symfony\Component\DependencyInjection\Extension\ExtensionInterface::class)->getMock(); + $extension = $this->createMock(ExtensionInterface::class); $extension->expects($this->exactly(2))->method('getAlias')->willReturn('project'); $extension->expects($this->once())->method('load')->with([['foo' => 'bar']]); @@ -1212,7 +1218,7 @@ public function testInlinedDefinitions() public function testThrowsCircularExceptionForCircularAliases() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException::class); + $this->expectException(ServiceCircularReferenceException::class); $this->expectExceptionMessage('Circular reference detected for service "app.test_class", path: "app.test_class -> App\TestClass -> app.test_class".'); $builder = new ContainerBuilder(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php b/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php index b9616f93e85a..30f690152d81 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php @@ -14,7 +14,9 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; +use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Contracts\Service\ResetInterface; @@ -168,7 +170,7 @@ public function testSetReplacesAlias() public function testSetWithNullOnInitializedPredefinedService() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "bar" service is already initialized, you cannot replace it.'); $sc = new Container(); $sc->set('foo', new \stdClass()); @@ -207,7 +209,7 @@ public function testGet() $sc->get(''); $this->fail('->get() throws a \InvalidArgumentException exception if the service is empty'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class, $e, '->get() throws a ServiceNotFoundException exception if the service is empty'); + $this->assertInstanceOf(ServiceNotFoundException::class, $e, '->get() throws a ServiceNotFoundException exception if the service is empty'); } $this->assertNull($sc->get('', ContainerInterface::NULL_ON_INVALID_REFERENCE), '->get() returns null if the service is empty'); } @@ -233,7 +235,7 @@ public function testGetThrowServiceNotFoundException() $sc->get('foo1'); $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class, $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist'); + $this->assertInstanceOf(ServiceNotFoundException::class, $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist'); $this->assertEquals('You have requested a non-existent service "foo1". Did you mean this: "foo"?', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException with some advices'); } @@ -241,7 +243,7 @@ public function testGetThrowServiceNotFoundException() $sc->get('bag'); $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class, $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist'); + $this->assertInstanceOf(ServiceNotFoundException::class, $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist'); $this->assertEquals('You have requested a non-existent service "bag". Did you mean one of these: "bar", "baz"?', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException with some advices'); } } @@ -260,7 +262,7 @@ public function testGetCircularReference() public function testGetSyntheticServiceThrows() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class); + $this->expectException(ServiceNotFoundException::class); $this->expectExceptionMessage('The "request" service is synthetic, it needs to be set at boot time before it can be used.'); require_once __DIR__.'/Fixtures/php/services9_compiled.php'; @@ -270,7 +272,7 @@ public function testGetSyntheticServiceThrows() public function testGetRemovedServiceThrows() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class); + $this->expectException(ServiceNotFoundException::class); $this->expectExceptionMessage('The "inlined" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.'); require_once __DIR__.'/Fixtures/php/services9_compiled.php'; @@ -410,7 +412,7 @@ public function testCheckExistenceOfAnInternalPrivateService() public function testRequestAnInternalSharedPrivateService() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class); + $this->expectException(ServiceNotFoundException::class); $this->expectExceptionMessage('You have requested a non-existent service "internal".'); $c = new ProjectServiceContainer(); $c->get('internal_dependency'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/DefinitionTest.php b/src/Symfony/Component/DependencyInjection/Tests/DefinitionTest.php index 45ec034ae29b..0a46e5795c79 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/DefinitionTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/DefinitionTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Parameter; use Symfony\Component\DependencyInjection\Reference; @@ -152,7 +153,7 @@ public function testMethodCalls() public function testExceptionOnEmptyMethodCall() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Method name cannot be empty.'); $def = new Definition('stdClass'); $def->addMethodCall(''); @@ -221,7 +222,7 @@ public function testSetIsDeprecated() */ public function testSetDeprecatedWithInvalidDeprecationTemplate($message) { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $def = new Definition('stdClass'); $def->setDeprecated(false, $message); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php index 707b014fba52..f088bcf3c36f 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php @@ -27,6 +27,10 @@ use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Dumper\PhpDumper; use Symfony\Component\DependencyInjection\EnvVarProcessorInterface; +use Symfony\Component\DependencyInjection\Exception\EnvParameterException; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Exception\LogicException; +use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; @@ -190,7 +194,7 @@ public function testAddParameters() public function testAddServiceWithoutCompilation() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Cannot dump an uncompiled container.'); $container = include self::$fixturesPath.'/containers/container9.php'; new PhpDumper($container); @@ -442,7 +446,7 @@ public function testFrozenContainerWithoutAliases() public function testOverrideServiceWhenUsingADumpedContainer() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "decorator_service" service is already initialized, you cannot replace it.'); require_once self::$fixturesPath.'/php/services9_compiled.php'; @@ -659,7 +663,7 @@ public function testFileEnvProcessor() public function testUnusedEnvParameter() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\EnvParameterException::class); + $this->expectException(EnvParameterException::class); $this->expectExceptionMessage('Environment variables "FOO" are never used. Please, check your container\'s configuration.'); $container = new ContainerBuilder(); $container->getParameter('env(FOO)'); @@ -670,7 +674,7 @@ public function testUnusedEnvParameter() public function testCircularDynamicEnv() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException::class); + $this->expectException(ParameterCircularReferenceException::class); $this->expectExceptionMessage('Circular reference detected for parameter "env(resolve:DUMMY_ENV_VAR)" ("env(resolve:DUMMY_ENV_VAR)" > "env(resolve:DUMMY_ENV_VAR)").'); $container = new ContainerBuilder(); $container->setParameter('foo', '%bar%'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PreloaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PreloaderTest.php index 9d3817e6cac4..5af562fcf363 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PreloaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PreloaderTest.php @@ -13,6 +13,14 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Dumper\Preloader; +use Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\A; +use Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\B; +use Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\C; +use Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\D; +use Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\Dummy; +use Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\DummyWithInterface; +use Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\E; +use Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\UnionDummy; class PreloaderTest extends TestCase { @@ -28,10 +36,10 @@ public function testPreload() $r->invokeArgs(null, ['Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\Dummy', &$preloaded]); - self::assertTrue(class_exists(\Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\Dummy::class, false)); - self::assertTrue(class_exists(\Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\A::class, false)); - self::assertTrue(class_exists(\Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\B::class, false)); - self::assertTrue(class_exists(\Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\C::class, false)); + self::assertTrue(class_exists(Dummy::class, false)); + self::assertTrue(class_exists(A::class, false)); + self::assertTrue(class_exists(B::class, false)); + self::assertTrue(class_exists(C::class, false)); } /** @@ -45,7 +53,7 @@ public function testPreloadSkipsNonExistingInterface() $preloaded = []; $r->invokeArgs(null, ['Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\DummyWithInterface', &$preloaded]); - self::assertFalse(class_exists(\Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\DummyWithInterface::class, false)); + self::assertFalse(class_exists(DummyWithInterface::class, false)); } /** @@ -60,8 +68,8 @@ public function testPreloadUnion() $r->invokeArgs(null, ['Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\UnionDummy', &$preloaded]); - self::assertTrue(class_exists(\Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\UnionDummy::class, false)); - self::assertTrue(class_exists(\Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\D::class, false)); - self::assertTrue(class_exists(\Symfony\Component\DependencyInjection\Tests\Fixtures\Preload\E::class, false)); + self::assertTrue(class_exists(UnionDummy::class, false)); + self::assertTrue(class_exists(D::class, false)); + self::assertTrue(class_exists(E::class, false)); } } diff --git a/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php b/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php index 80b10e0fb180..ab5f24b2ecba 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php @@ -8,6 +8,7 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\EnvVarLoaderInterface; use Symfony\Component\DependencyInjection\EnvVarProcessor; +use Symfony\Component\DependencyInjection\Exception\EnvNotFoundException; use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; @@ -376,7 +377,7 @@ public function noArrayValues() */ public function testGetEnvKeyArrayKeyNotFound($value) { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\EnvNotFoundException::class); + $this->expectException(EnvNotFoundException::class); $this->expectExceptionMessage('Key "index" not found in'); $processor = new EnvVarProcessor(new Container()); @@ -465,7 +466,7 @@ public function validNullables() public function testRequireMissingFile() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\EnvNotFoundException::class); + $this->expectException(EnvNotFoundException::class); $this->expectExceptionMessage('missing-file'); $processor = new EnvVarProcessor(new Container()); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Extension/ExtensionTest.php b/src/Symfony/Component/DependencyInjection/Tests/Extension/ExtensionTest.php index a781472ed348..44970163a842 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Extension/ExtensionTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Extension/ExtensionTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Extension\Extension; class ExtensionTest extends TestCase @@ -36,7 +37,7 @@ public function getResolvedEnabledFixtures() public function testIsConfigEnabledOnNonEnableableConfig() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The config array has no \'enabled\' key.'); $extension = new EnableableExtension(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/LazyProxy/Instantiator/RealServiceInstantiatorTest.php b/src/Symfony/Component/DependencyInjection/Tests/LazyProxy/Instantiator/RealServiceInstantiatorTest.php index fb97b31df347..4abbfdad3717 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/LazyProxy/Instantiator/RealServiceInstantiatorTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/LazyProxy/Instantiator/RealServiceInstantiatorTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\LazyProxy\Instantiator; use PHPUnit\Framework\TestCase; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator; @@ -26,7 +27,7 @@ public function testInstantiateProxy() { $instantiator = new RealServiceInstantiator(); $instance = new \stdClass(); - $container = $this->getMockBuilder(\Symfony\Component\DependencyInjection\ContainerInterface::class)->getMock(); + $container = $this->createMock(ContainerInterface::class); $callback = function () use ($instance) { return $instance; }; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php index 0570152fe59a..8362402ce954 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php @@ -18,6 +18,7 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Loader\FileLoader; use Symfony\Component\DependencyInjection\Loader\IniFileLoader; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; @@ -215,7 +216,7 @@ public function testMissingParentClass() public function testRegisterClassesWithBadPrefix() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageMatches('/Expected to find class "Symfony\\\Component\\\DependencyInjection\\\Tests\\\Fixtures\\\Prototype\\\Bar" in file ".+" while importing services from resource "Prototype\/Sub\/\*", but it was not found\! Check the namespace prefix used with the resource/'); $container = new ContainerBuilder(); $loader = new TestFileLoader($container, new FileLocator(self::$fixturesPath.'/Fixtures')); @@ -226,7 +227,7 @@ public function testRegisterClassesWithBadPrefix() public function testRegisterClassesWithIncompatibleExclude() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid "exclude" pattern when importing classes for "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\": make sure your "exclude" pattern (yaml/*) is a subset of the "resource" pattern (Prototype/*)'); $container = new ContainerBuilder(); $loader = new TestFileLoader($container, new FileLocator(self::$fixturesPath.'/Fixtures')); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.php index edbbb7012851..b4cf503237bc 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Loader\IniFileLoader; class IniFileLoaderTest extends TestCase @@ -99,14 +100,14 @@ public function testExceptionIsRaisedWhenIniFileDoesNotExist() public function testExceptionIsRaisedWhenIniFileCannotBeParsed() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "nonvalid.ini" file is not valid.'); @$this->loader->load('nonvalid.ini'); } public function testExceptionIsRaisedWhenIniFileIsAlmostValid() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "almostvalid.ini" file is not valid.'); @$this->loader->load('almostvalid.ini'); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.php index 98a7f0add009..e0ddd71f9d36 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.php @@ -16,6 +16,7 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Dumper\PhpDumper; use Symfony\Component\DependencyInjection\Dumper\YamlDumper; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; class PhpFileLoaderTest extends TestCase @@ -81,7 +82,7 @@ public function provideConfig() public function testAutoConfigureAndChildDefinitionNotAllowed() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The service "child_service" cannot have a "parent" and also have "autoconfigure". Try disabling autoconfiguration for the service.'); $fixtures = realpath(__DIR__.'/../Fixtures'); $container = new ContainerBuilder(); @@ -92,7 +93,7 @@ public function testAutoConfigureAndChildDefinitionNotAllowed() public function testFactoryShortNotationNotAllowed() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid factory "factory:method": the "service:method" notation is not available when using PHP-based DI configuration. Use "[ref(\'factory\'), \'method\']" instead.'); $fixtures = realpath(__DIR__.'/../Fixtures'); $container = new ContainerBuilder(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php index cb35f1cae673..aa0d08ed184d 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\DependencyInjection\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Exception\FileLocatorFileNotFoundException; +use Symfony\Component\Config\Exception\LoaderLoadException; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Config\Resource\GlobResource; +use Symfony\Component\Config\Util\Exception\XmlParsingException; use Symfony\Component\DependencyInjection\Argument\BoundArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument; @@ -23,7 +26,9 @@ use Symfony\Component\DependencyInjection\Compiler\ResolveBindingsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Dumper\PhpDumper; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Loader\IniFileLoader; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; @@ -71,7 +76,7 @@ public function testParseFile() $m->invoke($loader, self::$fixturesPath.'/ini/parameters.ini'); $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class, $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); + $this->assertInstanceOf(InvalidArgumentException::class, $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $this->assertMatchesRegularExpression(sprintf('#^Unable to parse file ".+%s": .+.$#', 'parameters.ini'), $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $e = $e->getPrevious(); @@ -85,7 +90,7 @@ public function testParseFile() $m->invoke($loader, self::$fixturesPath.'/xml/nonvalid.xml'); $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class, $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); + $this->assertInstanceOf(InvalidArgumentException::class, $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); $this->assertMatchesRegularExpression(sprintf('#^Unable to parse file ".+%s": .+.$#', 'nonvalid.xml'), $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $e = $e->getPrevious(); @@ -195,11 +200,11 @@ public function testLoadImports() $loader->load('services4_bad_import_with_errors.xml'); $this->fail('->load() throws a LoaderLoadException if the imported xml file configuration does not exist'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\Config\Exception\LoaderLoadException::class, $e, '->load() throws a LoaderLoadException if the imported xml file configuration does not exist'); + $this->assertInstanceOf(LoaderLoadException::class, $e, '->load() throws a LoaderLoadException if the imported xml file configuration does not exist'); $this->assertMatchesRegularExpression(sprintf('#^The file "%1$s" does not exist \(in: .+\) in %1$s \(which is being imported from ".+%2$s"\)\.$#', 'foo_fake\.xml', 'services4_bad_import_with_errors\.xml'), $e->getMessage(), '->load() throws a LoaderLoadException if the imported xml file configuration does not exist'); $e = $e->getPrevious(); - $this->assertInstanceOf(\Symfony\Component\Config\Exception\FileLocatorFileNotFoundException::class, $e, '->load() throws a FileLocatorFileNotFoundException if the imported xml file configuration does not exist'); + $this->assertInstanceOf(FileLocatorFileNotFoundException::class, $e, '->load() throws a FileLocatorFileNotFoundException if the imported xml file configuration does not exist'); $this->assertMatchesRegularExpression(sprintf('#^The file "%s" does not exist \(in: .+\)\.$#', 'foo_fake\.xml'), $e->getMessage(), '->load() throws a FileLocatorFileNotFoundException if the imported xml file configuration does not exist'); } @@ -207,15 +212,15 @@ public function testLoadImports() $loader->load('services4_bad_import_nonvalid.xml'); $this->fail('->load() throws an LoaderLoadException if the imported configuration does not validate the XSD'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\Config\Exception\LoaderLoadException::class, $e, '->load() throws a LoaderLoadException if the imported configuration does not validate the XSD'); + $this->assertInstanceOf(LoaderLoadException::class, $e, '->load() throws a LoaderLoadException if the imported configuration does not validate the XSD'); $this->assertMatchesRegularExpression(sprintf('#^Unable to parse file ".+%s": .+.$#', 'nonvalid\.xml'), $e->getMessage(), '->load() throws a LoaderLoadException if the imported configuration does not validate the XSD'); $e = $e->getPrevious(); - $this->assertInstanceOf(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class, $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); + $this->assertInstanceOf(InvalidArgumentException::class, $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $this->assertMatchesRegularExpression(sprintf('#^Unable to parse file ".+%s": .+.$#', 'nonvalid\.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $e = $e->getPrevious(); - $this->assertInstanceOf(\Symfony\Component\Config\Util\Exception\XmlParsingException::class, $e, '->load() throws a XmlParsingException if the configuration does not validate the XSD'); + $this->assertInstanceOf(XmlParsingException::class, $e, '->load() throws a XmlParsingException if the configuration does not validate the XSD'); $this->assertStringStartsWith('[ERROR 1845] Element \'nonvalid\': No matching global declaration available for the validation root. (in', $e->getMessage(), '->load() throws a XmlParsingException if the loaded file does not validate the XSD'); } } @@ -265,7 +270,7 @@ public function testLoadAnonymousServices() public function testLoadAnonymousServicesWithoutId() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Top-level services must have "id" attribute, none found in'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); @@ -291,7 +296,7 @@ public function testLoadServices() $services = $container->getDefinitions(); $this->assertArrayHasKey('foo', $services, '->load() parses elements'); $this->assertFalse($services['not_shared']->isShared(), '->load() parses shared flag'); - $this->assertInstanceOf(\Symfony\Component\DependencyInjection\Definition::class, $services['foo'], '->load() converts element to Definition instances'); + $this->assertInstanceOf(Definition::class, $services['foo'], '->load() converts element to Definition instances'); $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute'); $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag'); $this->assertEquals(['foo', new Reference('foo'), [true, false]], $services['arguments']->getArguments(), '->load() parses the argument tags'); @@ -373,7 +378,7 @@ public function testParseTaggedArgumentsWithIndexBy() public function testParseTagsWithoutNameThrowsException() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('tag_without_name.xml'); @@ -381,7 +386,7 @@ public function testParseTagsWithoutNameThrowsException() public function testParseTagWithEmptyNameThrowsException() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageMatches('/The tag name for service ".+" in .* must be a non-empty string/'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); @@ -494,7 +499,7 @@ public function testExtensions() $loader->load('extensions/services3.xml'); $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class, $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); + $this->assertInstanceOf(InvalidArgumentException::class, $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $this->assertMatchesRegularExpression(sprintf('#^Unable to parse file ".+%s": .+.$#', 'services3.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $e = $e->getPrevious(); @@ -531,7 +536,7 @@ public function testExtensionInPhar() $loader->load('extensions/services7.xml'); $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class, $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); + $this->assertInstanceOf(InvalidArgumentException::class, $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $this->assertMatchesRegularExpression(sprintf('#^Unable to parse file ".+%s": .+.$#', 'services7.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $e = $e->getPrevious(); @@ -582,7 +587,7 @@ public function testDocTypeIsNotAllowed() $loader->load('withdoctype.xml'); $this->fail('->load() throws an InvalidArgumentException if the configuration contains a document type'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class, $e, '->load() throws an InvalidArgumentException if the configuration contains a document type'); + $this->assertInstanceOf(InvalidArgumentException::class, $e, '->load() throws an InvalidArgumentException if the configuration contains a document type'); $this->assertMatchesRegularExpression(sprintf('#^Unable to parse file ".+%s": .+.$#', 'withdoctype.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type'); $e = $e->getPrevious(); @@ -731,7 +736,7 @@ public function testPrototypeExcludeWithArray() public function testAliasDefinitionContainsUnsupportedElements() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid attribute "class" defined for alias "bar" in'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); @@ -814,7 +819,7 @@ public function testInstanceof() public function testInstanceOfAndChildDefinitionNotAllowed() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The service "child_service" cannot use the "parent" option in the same file where "instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file.'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); @@ -824,7 +829,7 @@ public function testInstanceOfAndChildDefinitionNotAllowed() public function testAutoConfigureAndChildDefinitionNotAllowed() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The service "child_service" cannot have a "parent" and also have "autoconfigure". Try setting autoconfigure="false" for the service.'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); @@ -834,7 +839,7 @@ public function testAutoConfigureAndChildDefinitionNotAllowed() public function testDefaultsAndChildDefinitionNotAllowed() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Attribute "autowire" on service "child_service" cannot be inherited from "defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly.'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php index 71142af2966f..2e15f615fb5e 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\DependencyInjection\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Exception\FileLocatorFileNotFoundException; +use Symfony\Component\Config\Exception\LoaderLoadException; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\Resource\FileResource; @@ -23,7 +25,9 @@ use Symfony\Component\DependencyInjection\Compiler\ResolveBindingsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Loader\IniFileLoader; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; @@ -35,6 +39,7 @@ use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy; use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype; use Symfony\Component\ExpressionLanguage\Expression; +use Symfony\Component\Yaml\Exception\ExceptionInterface; class YamlFileLoaderTest extends TestCase { @@ -143,11 +148,11 @@ public function testLoadImports() $loader->load('services4_bad_import_with_errors.yml'); $this->fail('->load() throws a LoaderLoadException if the imported yaml file does not exist'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\Config\Exception\LoaderLoadException::class, $e, '->load() throws a LoaderLoadException if the imported yaml file does not exist'); + $this->assertInstanceOf(LoaderLoadException::class, $e, '->load() throws a LoaderLoadException if the imported yaml file does not exist'); $this->assertMatchesRegularExpression(sprintf('#^The file "%1$s" does not exist \(in: .+\) in %1$s \(which is being imported from ".+%2$s"\)\.$#', 'foo_fake\.yml', 'services4_bad_import_with_errors\.yml'), $e->getMessage(), '->load() throws a LoaderLoadException if the imported yaml file does not exist'); $e = $e->getPrevious(); - $this->assertInstanceOf(\Symfony\Component\Config\Exception\FileLocatorFileNotFoundException::class, $e, '->load() throws a FileLocatorFileNotFoundException if the imported yaml file does not exist'); + $this->assertInstanceOf(FileLocatorFileNotFoundException::class, $e, '->load() throws a FileLocatorFileNotFoundException if the imported yaml file does not exist'); $this->assertMatchesRegularExpression(sprintf('#^The file "%s" does not exist \(in: .+\)\.$#', 'foo_fake\.yml'), $e->getMessage(), '->load() throws a FileLocatorFileNotFoundException if the imported yaml file does not exist'); } @@ -155,7 +160,7 @@ public function testLoadImports() $loader->load('services4_bad_import_nonvalid.yml'); $this->fail('->load() throws a LoaderLoadException if the tag in the imported yaml file is not valid'); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\Config\Exception\LoaderLoadException::class, $e, '->load() throws a LoaderLoadException if the tag in the imported yaml file is not valid'); + $this->assertInstanceOf(LoaderLoadException::class, $e, '->load() throws a LoaderLoadException if the tag in the imported yaml file is not valid'); $this->assertMatchesRegularExpression(sprintf('#^The service file ".+%1$s" is not valid\. It should contain an array\. Check your YAML syntax in .+%1$s \(which is being imported from ".+%2$s"\)\.$#', 'nonvalid2\.yml', 'services4_bad_import_nonvalid.yml'), $e->getMessage(), '->load() throws a LoaderLoadException if the tag in the imported yaml file is not valid'); $e = $e->getPrevious(); @@ -172,7 +177,7 @@ public function testLoadServices() $services = $container->getDefinitions(); $this->assertArrayHasKey('foo', $services, '->load() parses service elements'); $this->assertFalse($services['not_shared']->isShared(), '->load() parses the shared flag'); - $this->assertInstanceOf(\Symfony\Component\DependencyInjection\Definition::class, $services['foo'], '->load() converts service element to Definition instances'); + $this->assertInstanceOf(Definition::class, $services['foo'], '->load() converts service element to Definition instances'); $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute'); $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag'); $this->assertEquals(['foo', new Reference('foo'), [true, false]], $services['arguments']->getArguments(), '->load() parses the argument tags'); @@ -352,7 +357,7 @@ public function testTaggedArgumentsWithIndex() $taggedIterator = new TaggedIteratorArgument('foo', 'barfoo', 'foobar', true, 'getPriority'); $this->assertEquals(new ServiceLocatorArgument($taggedIterator), $container->getDefinition('foo_service_tagged_locator')->getArgument(0)); - if (is_subclass_of(\Symfony\Component\Yaml\Exception\ExceptionInterface::class, 'Throwable')) { + if (is_subclass_of(ExceptionInterface::class, 'Throwable')) { // this test is not compatible with Yaml v3 $taggedIterator = new TaggedIteratorArgument('foo', null, null, true); $this->assertEquals(new ServiceLocatorArgument($taggedIterator), $container->getDefinition('bar_service_tagged_locator')->getArgument(0)); @@ -835,7 +840,7 @@ public function testBindings() public function testProcessNotExistingActionParam() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Cannot autowire service "Symfony\Component\DependencyInjection\Tests\Fixtures\ConstructNotExists": argument "$notExist" of method "__construct()" has type "Symfony\Component\DependencyInjection\Tests\Fixtures\NotExist" but this class was not found.'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); diff --git a/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/ContainerBagTest.php b/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/ContainerBagTest.php index c4c690c59204..b01442d462f9 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/ContainerBagTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/ContainerBagTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use Symfony\Component\DependencyInjection\Container; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\ParameterBag\ContainerBag; use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface; use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; @@ -50,7 +51,7 @@ public function testGetParameter() public function testGetParameterNotFound() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->containerBag->get('bar'); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php b/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php index a6c929d88013..286d9b7a1fa0 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php @@ -12,13 +12,15 @@ namespace Symfony\Component\DependencyInjection\Tests\ParameterBag; use PHPUnit\Framework\TestCase; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag; class EnvPlaceholderParameterBagTest extends TestCase { public function testGetThrowsInvalidArgumentExceptionIfEnvNameContainsNonWordCharacters() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $bag = new EnvPlaceholderParameterBag(); $bag->get('env(%foo%)'); } @@ -161,7 +163,7 @@ public function testResolveEnvAllowsNull() public function testResolveThrowsOnBadDefaultValue() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The default value of env parameter "ARRAY_VAR" must be scalar or null, "array" given.'); $bag = new EnvPlaceholderParameterBag(); $bag->get('env(ARRAY_VAR)'); @@ -181,7 +183,7 @@ public function testGetEnvAllowsNull() public function testGetThrowsOnBadDefaultValue() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The default value of an env() parameter must be scalar or null, but "array" given to "env(ARRAY_VAR)".'); $bag = new EnvPlaceholderParameterBag(); $bag->set('env(ARRAY_VAR)', []); diff --git a/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php b/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php index 7e415b226a55..e03f9fc55585 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php @@ -11,7 +11,10 @@ namespace Symfony\Component\DependencyInjection\Tests; +use Psr\Container\NotFoundExceptionInterface; use Symfony\Component\DependencyInjection\Container; +use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; +use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\ServiceLocator; use Symfony\Contracts\Service\ServiceSubscriberInterface; use Symfony\Contracts\Service\Test\ServiceLocatorTest as BaseServiceLocatorTest; @@ -25,7 +28,7 @@ public function getServiceLocator(array $factories) public function testGetThrowsOnUndefinedService() { - $this->expectException(\Psr\Container\NotFoundExceptionInterface::class); + $this->expectException(NotFoundExceptionInterface::class); $this->expectExceptionMessage('Service "dummy" not found: the container inside "Symfony\Component\DependencyInjection\Tests\ServiceLocatorTest" is a smaller service locator that only knows about the "foo" and "bar" services.'); $locator = $this->getServiceLocator([ 'foo' => function () { return 'bar'; }, @@ -37,14 +40,14 @@ public function testGetThrowsOnUndefinedService() public function testThrowsOnCircularReference() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException::class); + $this->expectException(ServiceCircularReferenceException::class); $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> baz -> bar".'); parent::testThrowsOnCircularReference(); } public function testThrowsInServiceSubscriber() { - $this->expectException(\Psr\Container\NotFoundExceptionInterface::class); + $this->expectException(NotFoundExceptionInterface::class); $this->expectExceptionMessage('Service "foo" not found: even though it exists in the app\'s container, the container inside "caller" is a smaller service locator that only knows about the "bar" service. Unless you need extra laziness, try using dependency injection instead. Otherwise, you need to declare it using "SomeServiceSubscriber::getSubscribedServices()".'); $container = new Container(); $container->set('foo', new \stdClass()); @@ -57,7 +60,7 @@ public function testThrowsInServiceSubscriber() public function testGetThrowsServiceNotFoundException() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException::class); + $this->expectException(ServiceNotFoundException::class); $this->expectExceptionMessage('Service "foo" not found: even though it exists in the app\'s container, the container inside "foo" is a smaller service locator that is empty... Try using dependency injection instead.'); $container = new Container(); $container->set('foo', new \stdClass()); diff --git a/src/Symfony/Component/DomCrawler/Tests/AbstractCrawlerTest.php b/src/Symfony/Component/DomCrawler/Tests/AbstractCrawlerTest.php index 9868e49c533c..697306c53ee2 100644 --- a/src/Symfony/Component/DomCrawler/Tests/AbstractCrawlerTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/AbstractCrawlerTest.php @@ -13,6 +13,9 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DomCrawler\Crawler; +use Symfony\Component\DomCrawler\Form; +use Symfony\Component\DomCrawler\Image; +use Symfony\Component\DomCrawler\Link; abstract class AbstractCrawlerTest extends TestCase { @@ -719,7 +722,7 @@ public function testSelectButtonWithDoubleQuotesInNameAttribute() public function testLink() { $crawler = $this->createTestCrawler('http://example.com/bar/')->selectLink('Foo'); - $this->assertInstanceOf(\Symfony\Component\DomCrawler\Link::class, $crawler->link(), '->link() returns a Link instance'); + $this->assertInstanceOf(Link::class, $crawler->link(), '->link() returns a Link instance'); $this->assertEquals('POST', $crawler->link('post')->getMethod(), '->link() takes a method as its argument'); @@ -753,7 +756,7 @@ public function testInvalidLinks() public function testImage() { $crawler = $this->createTestCrawler('http://example.com/bar/')->selectImage('Bar'); - $this->assertInstanceOf(\Symfony\Component\DomCrawler\Image::class, $crawler->image(), '->image() returns an Image instance'); + $this->assertInstanceOf(Image::class, $crawler->image(), '->image() returns an Image instance'); try { $this->createTestCrawler()->filterXPath('//ol')->image(); @@ -829,8 +832,8 @@ public function testForm() $testCrawler = $this->createTestCrawler('http://example.com/bar/'); $crawler = $testCrawler->selectButton('FooValue'); $crawler2 = $testCrawler->selectButton('FooBarValue'); - $this->assertInstanceOf(\Symfony\Component\DomCrawler\Form::class, $crawler->form(), '->form() returns a Form instance'); - $this->assertInstanceOf(\Symfony\Component\DomCrawler\Form::class, $crawler2->form(), '->form() returns a Form instance'); + $this->assertInstanceOf(Form::class, $crawler->form(), '->form() returns a Form instance'); + $this->assertInstanceOf(Form::class, $crawler2->form(), '->form() returns a Form instance'); $this->assertEquals($crawler->form()->getFormNode()->getAttribute('id'), $crawler2->form()->getFormNode()->getAttribute('id'), '->form() works on elements with form attribute'); diff --git a/src/Symfony/Component/DomCrawler/Tests/FormTest.php b/src/Symfony/Component/DomCrawler/Tests/FormTest.php index 52a59090c1bf..3b29b0f588ff 100644 --- a/src/Symfony/Component/DomCrawler/Tests/FormTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/FormTest.php @@ -12,6 +12,9 @@ namespace Symfony\Component\DomCrawler\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\DomCrawler\Field\ChoiceFormField; +use Symfony\Component\DomCrawler\Field\FormField; +use Symfony\Component\DomCrawler\Field\InputFormField; use Symfony\Component\DomCrawler\Field\TextareaFormField; use Symfony\Component\DomCrawler\Form; use Symfony\Component\DomCrawler\FormFieldRegistry; @@ -682,7 +685,7 @@ public function testGet() { $form = $this->createForm('
'); - $this->assertInstanceOf(\Symfony\Component\DomCrawler\Field\InputFormField::class, $form->get('bar'), '->get() returns the field object associated with the given name'); + $this->assertInstanceOf(InputFormField::class, $form->get('bar'), '->get() returns the field object associated with the given name'); try { $form->get('foo'); @@ -698,7 +701,7 @@ public function testAll() $fields = $form->all(); $this->assertCount(1, $fields, '->all() return an array of form field objects'); - $this->assertInstanceOf(\Symfony\Component\DomCrawler\Field\InputFormField::class, $fields['bar'], '->all() return an array of form field objects'); + $this->assertInstanceOf(InputFormField::class, $fields['bar'], '->all() return an array of form field objects'); } public function testSubmitWithoutAFormButton() @@ -864,13 +867,13 @@ public function testDifferentFieldTypesWithSameName() '); $form = new Form($dom->getElementsByTagName('form')->item(0), 'http://example.com'); - $this->assertInstanceOf(\Symfony\Component\DomCrawler\Field\ChoiceFormField::class, $form->get('option')); + $this->assertInstanceOf(ChoiceFormField::class, $form->get('option')); } protected function getFormFieldMock($name, $value = null) { $field = $this - ->getMockBuilder(\Symfony\Component\DomCrawler\Field\FormField::class) + ->getMockBuilder(FormField::class) ->setMethods(['getName', 'getValue', 'setValue', 'initialize']) ->disableOriginalConstructor() ->getMock() diff --git a/src/Symfony/Component/Dotenv/Tests/DotenvTest.php b/src/Symfony/Component/Dotenv/Tests/DotenvTest.php index c375efe47d04..3df51a5392e6 100644 --- a/src/Symfony/Component/Dotenv/Tests/DotenvTest.php +++ b/src/Symfony/Component/Dotenv/Tests/DotenvTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Dotenv\Dotenv; use Symfony\Component\Dotenv\Exception\FormatException; +use Symfony\Component\Dotenv\Exception\PathException; class DotenvTest extends TestCase { @@ -322,7 +323,7 @@ public function testOverload() public function testLoadDirectory() { - $this->expectException(\Symfony\Component\Dotenv\Exception\PathException::class); + $this->expectException(PathException::class); $dotenv = new Dotenv(true); $dotenv->load(__DIR__); } diff --git a/src/Symfony/Component/ErrorHandler/Tests/DebugClassLoaderTest.php b/src/Symfony/Component/ErrorHandler/Tests/DebugClassLoaderTest.php index 141459f72c69..84c930edb041 100644 --- a/src/Symfony/Component/ErrorHandler/Tests/DebugClassLoaderTest.php +++ b/src/Symfony/Component/ErrorHandler/Tests/DebugClassLoaderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\ErrorHandler\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\ErrorHandler\Tests\Fixtures\ExtendsDeprecatedParent; use Symfony\Component\ErrorHandler\DebugClassLoader; class DebugClassLoaderTest extends TestCase @@ -176,7 +177,7 @@ public function testDeprecatedSuperInSameNamespace() $e = error_reporting(0); trigger_error('', E_USER_NOTICE); - class_exists(\Symfony\Bridge\ErrorHandler\Tests\Fixtures\ExtendsDeprecatedParent::class, true); + class_exists(ExtendsDeprecatedParent::class, true); error_reporting($e); restore_error_handler(); diff --git a/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php b/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php index f3f67b9716d2..8603bf825dec 100644 --- a/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php +++ b/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\ErrorHandler\Tests; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; use Psr\Log\NullLogger; use Symfony\Component\ErrorHandler\BufferingLogger; @@ -62,7 +63,7 @@ public function testRegister() public function testErrorGetLast() { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $handler = ErrorHandler::register(); $handler->setDefaultLogger($logger); $handler->screamAt(\E_ALL); @@ -194,7 +195,7 @@ public function testConstruct() public function testDefaultLogger() { try { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $handler = ErrorHandler::register(); $handler->setDefaultLogger($logger, \E_NOTICE); @@ -269,7 +270,7 @@ public function testHandleError() restore_error_handler(); restore_exception_handler(); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $warnArgCheck = function ($logLevel, $message, $context) { $this->assertEquals('info', $logLevel); @@ -294,7 +295,7 @@ public function testHandleError() restore_error_handler(); restore_exception_handler(); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $line = null; $logArgCheck = function ($level, $message, $context) use (&$line) { @@ -395,7 +396,7 @@ public function testHandleDeprecation() $this->assertSame('User Deprecated: Foo deprecation', $exception->getMessage()); }; - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $logger ->expects($this->once()) ->method('log') @@ -413,7 +414,7 @@ public function testHandleDeprecation() public function testHandleException(string $expectedMessage, \Throwable $exception) { try { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $handler = ErrorHandler::register(); $logArgCheck = function ($level, $message, $context) use ($expectedMessage, $exception) { @@ -505,7 +506,7 @@ public function testBootstrappingLogger() $bootLogger->log(LogLevel::WARNING, 'Foo message', ['exception' => $exception]); - $mockLogger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $mockLogger = $this->createMock(LoggerInterface::class); $mockLogger->expects($this->once()) ->method('log') ->with(LogLevel::WARNING, 'Foo message', ['exception' => $exception]); @@ -520,7 +521,7 @@ public function testSettingLoggerWhenExceptionIsBuffered() $exception = new \Exception('Foo message'); - $mockLogger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $mockLogger = $this->createMock(LoggerInterface::class); $mockLogger->expects($this->once()) ->method('log') ->with(LogLevel::CRITICAL, 'Uncaught Exception: Foo message', ['exception' => $exception]); @@ -535,7 +536,7 @@ public function testSettingLoggerWhenExceptionIsBuffered() public function testHandleFatalError() { try { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $handler = ErrorHandler::register(); $error = [ diff --git a/src/Symfony/Component/EventDispatcher/Tests/Debug/WrappedListenerTest.php b/src/Symfony/Component/EventDispatcher/Tests/Debug/WrappedListenerTest.php index 75e90120736e..6564d23f3220 100644 --- a/src/Symfony/Component/EventDispatcher/Tests/Debug/WrappedListenerTest.php +++ b/src/Symfony/Component/EventDispatcher/Tests/Debug/WrappedListenerTest.php @@ -23,7 +23,7 @@ class WrappedListenerTest extends TestCase */ public function testListenerDescription($listener, $expected) { - $wrappedListener = new WrappedListener($listener, null, $this->getMockBuilder(Stopwatch::class)->getMock(), $this->getMockBuilder(EventDispatcherInterface::class)->getMock()); + $wrappedListener = new WrappedListener($listener, null, $this->createMock(Stopwatch::class), $this->createMock(EventDispatcherInterface::class)); $this->assertStringMatchesFormat($expected, $wrappedListener->getPretty()); } diff --git a/src/Symfony/Component/EventDispatcher/Tests/EventDispatcherTest.php b/src/Symfony/Component/EventDispatcher/Tests/EventDispatcherTest.php index c3ed0cf20b1a..32f242e6f100 100644 --- a/src/Symfony/Component/EventDispatcher/Tests/EventDispatcherTest.php +++ b/src/Symfony/Component/EventDispatcher/Tests/EventDispatcherTest.php @@ -228,7 +228,7 @@ public function testAddSubscriberWithPriorities() $listeners = $this->dispatcher->getListeners('pre.foo'); $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); $this->assertCount(2, $listeners); - $this->assertInstanceOf(\Symfony\Component\EventDispatcher\Tests\TestEventSubscriberWithPriorities::class, $listeners[0][0]); + $this->assertInstanceOf(TestEventSubscriberWithPriorities::class, $listeners[0][0]); } public function testAddSubscriberWithMultipleListeners() diff --git a/src/Symfony/Component/EventDispatcher/Tests/ImmutableEventDispatcherTest.php b/src/Symfony/Component/EventDispatcher/Tests/ImmutableEventDispatcherTest.php index ce6eeaaa70dc..be91f65d7275 100644 --- a/src/Symfony/Component/EventDispatcher/Tests/ImmutableEventDispatcherTest.php +++ b/src/Symfony/Component/EventDispatcher/Tests/ImmutableEventDispatcherTest.php @@ -14,6 +14,8 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\EventDispatcher\ImmutableEventDispatcher; /** @@ -33,7 +35,7 @@ class ImmutableEventDispatcherTest extends TestCase protected function setUp(): void { - $this->innerDispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class)->getMock(); + $this->innerDispatcher = $this->createMock(EventDispatcherInterface::class); $this->dispatcher = new ImmutableEventDispatcher($this->innerDispatcher); } @@ -79,7 +81,7 @@ public function testAddListenerDisallowed() public function testAddSubscriberDisallowed() { $this->expectException(\BadMethodCallException::class); - $subscriber = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventSubscriberInterface::class)->getMock(); + $subscriber = $this->createMock(EventSubscriberInterface::class); $this->dispatcher->addSubscriber($subscriber); } @@ -93,7 +95,7 @@ public function testRemoveListenerDisallowed() public function testRemoveSubscriberDisallowed() { $this->expectException(\BadMethodCallException::class); - $subscriber = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventSubscriberInterface::class)->getMock(); + $subscriber = $this->createMock(EventSubscriberInterface::class); $this->dispatcher->removeSubscriber($subscriber); } diff --git a/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php b/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php index 4311e98eef2f..5db40cf58afc 100644 --- a/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php +++ b/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php @@ -12,17 +12,20 @@ namespace Symfony\Component\ExpressionLanguage\Tests; use PHPUnit\Framework\TestCase; +use Psr\Cache\CacheItemInterface; +use Psr\Cache\CacheItemPoolInterface; use Symfony\Component\ExpressionLanguage\ExpressionFunction; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Symfony\Component\ExpressionLanguage\ParsedExpression; +use Symfony\Component\ExpressionLanguage\SyntaxError; use Symfony\Component\ExpressionLanguage\Tests\Fixtures\TestProvider; class ExpressionLanguageTest extends TestCase { public function testCachedParse() { - $cacheMock = $this->getMockBuilder(\Psr\Cache\CacheItemPoolInterface::class)->getMock(); - $cacheItemMock = $this->getMockBuilder(\Psr\Cache\CacheItemInterface::class)->getMock(); + $cacheMock = $this->createMock(CacheItemPoolInterface::class); + $cacheItemMock = $this->createMock(CacheItemInterface::class); $savedParsedExpression = null; $expressionLanguage = new ExpressionLanguage($cacheMock); @@ -107,7 +110,7 @@ public function testShortCircuitOperatorsCompile($expression, array $names, $exp public function testParseThrowsInsteadOfNotice() { - $this->expectException(\Symfony\Component\ExpressionLanguage\SyntaxError::class); + $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unexpected end of expression around position 6 for expression `node.`.'); $expressionLanguage = new ExpressionLanguage(); $expressionLanguage->parse('node.', ['node']); @@ -155,8 +158,8 @@ public function testStrictEquality() public function testCachingWithDifferentNamesOrder() { - $cacheMock = $this->getMockBuilder(\Psr\Cache\CacheItemPoolInterface::class)->getMock(); - $cacheItemMock = $this->getMockBuilder(\Psr\Cache\CacheItemInterface::class)->getMock(); + $cacheMock = $this->createMock(CacheItemPoolInterface::class); + $cacheItemMock = $this->createMock(CacheItemInterface::class); $expressionLanguage = new ExpressionLanguage($cacheMock); $savedParsedExpression = null; diff --git a/src/Symfony/Component/ExpressionLanguage/Tests/LexerTest.php b/src/Symfony/Component/ExpressionLanguage/Tests/LexerTest.php index c909eacc253e..29d170d739be 100644 --- a/src/Symfony/Component/ExpressionLanguage/Tests/LexerTest.php +++ b/src/Symfony/Component/ExpressionLanguage/Tests/LexerTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\ExpressionLanguage\Lexer; +use Symfony\Component\ExpressionLanguage\SyntaxError; use Symfony\Component\ExpressionLanguage\Token; use Symfony\Component\ExpressionLanguage\TokenStream; @@ -39,7 +40,7 @@ public function testTokenize($tokens, $expression) public function testTokenizeThrowsErrorWithMessage() { - $this->expectException(\Symfony\Component\ExpressionLanguage\SyntaxError::class); + $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unexpected character "\'" around position 33 for expression `service(faulty.expression.example\').dummyMethod()`.'); $expression = "service(faulty.expression.example').dummyMethod()"; $this->lexer->tokenize($expression); @@ -47,7 +48,7 @@ public function testTokenizeThrowsErrorWithMessage() public function testTokenizeThrowsErrorOnUnclosedBrace() { - $this->expectException(\Symfony\Component\ExpressionLanguage\SyntaxError::class); + $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unclosed "(" around position 7 for expression `service(unclosed.expression.dummyMethod()`.'); $expression = 'service(unclosed.expression.dummyMethod()'; $this->lexer->tokenize($expression); diff --git a/src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php b/src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php index ef8fcb6ba13c..a57397143993 100644 --- a/src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php +++ b/src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php @@ -15,12 +15,13 @@ use Symfony\Component\ExpressionLanguage\Lexer; use Symfony\Component\ExpressionLanguage\Node; use Symfony\Component\ExpressionLanguage\Parser; +use Symfony\Component\ExpressionLanguage\SyntaxError; class ParserTest extends TestCase { public function testParseWithInvalidName() { - $this->expectException(\Symfony\Component\ExpressionLanguage\SyntaxError::class); + $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Variable "foo" is not valid around position 1 for expression `foo`.'); $lexer = new Lexer(); $parser = new Parser([]); @@ -29,7 +30,7 @@ public function testParseWithInvalidName() public function testParseWithZeroInNames() { - $this->expectException(\Symfony\Component\ExpressionLanguage\SyntaxError::class); + $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Variable "foo" is not valid around position 1 for expression `foo`.'); $lexer = new Lexer(); $parser = new Parser([]); @@ -197,7 +198,7 @@ private function createGetAttrNode($node, $item, $type) */ public function testParseWithInvalidPostfixData($expr, $names = []) { - $this->expectException(\Symfony\Component\ExpressionLanguage\SyntaxError::class); + $this->expectException(SyntaxError::class); $lexer = new Lexer(); $parser = new Parser([]); $parser->parse($lexer->tokenize($expr), $names); @@ -227,7 +228,7 @@ public function getInvalidPostfixData() public function testNameProposal() { - $this->expectException(\Symfony\Component\ExpressionLanguage\SyntaxError::class); + $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Did you mean "baz"?'); $lexer = new Lexer(); $parser = new Parser([]); diff --git a/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php b/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php index a0de640d03bc..c5f1674c4e37 100644 --- a/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php +++ b/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Filesystem\Tests; +use Symfony\Component\Filesystem\Exception\InvalidArgumentException; use Symfony\Component\Filesystem\Exception\IOException; /** @@ -1150,14 +1151,14 @@ public function providePathsForMakePathRelative() public function testMakePathRelativeWithRelativeStartPath() { - $this->expectException(\Symfony\Component\Filesystem\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The start path "var/lib/symfony/src/Symfony/Component" is not absolute.'); $this->assertSame('../../../', $this->filesystem->makePathRelative('/var/lib/symfony/', 'var/lib/symfony/src/Symfony/Component')); } public function testMakePathRelativeWithRelativeEndPath() { - $this->expectException(\Symfony\Component\Filesystem\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The end path "var/lib/symfony/" is not absolute.'); $this->assertSame('../../../', $this->filesystem->makePathRelative('var/lib/symfony/', '/var/lib/symfony/src/Symfony/Component')); } diff --git a/src/Symfony/Component/Finder/Tests/FinderTest.php b/src/Symfony/Component/Finder/Tests/FinderTest.php index f1a3af4321a8..db3c4a55ef7b 100644 --- a/src/Symfony/Component/Finder/Tests/FinderTest.php +++ b/src/Symfony/Component/Finder/Tests/FinderTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Finder\Tests; +use Symfony\Component\Finder\Exception\DirectoryNotFoundException; use Symfony\Component\Finder\Finder; class FinderTest extends Iterator\RealIteratorTestCase @@ -923,7 +924,7 @@ public function testIn() public function testInWithNonExistentDirectory() { - $this->expectException(\Symfony\Component\Finder\Exception\DirectoryNotFoundException::class); + $this->expectException(DirectoryNotFoundException::class); $finder = new Finder(); $finder->in('foobar'); } diff --git a/src/Symfony/Component/Form/Test/Traits/ValidatorExtensionTrait.php b/src/Symfony/Component/Form/Test/Traits/ValidatorExtensionTrait.php index e7f7d0e0c411..8ceb9761ec36 100644 --- a/src/Symfony/Component/Form/Test/Traits/ValidatorExtensionTrait.php +++ b/src/Symfony/Component/Form/Test/Traits/ValidatorExtensionTrait.php @@ -37,7 +37,7 @@ protected function getValidatorExtension() throw new \Exception(sprintf('The trait "ValidatorExtensionTrait" can only be added to a class that extends "%s".', TypeTestCase::class)); } - $this->validator = $this->getMockBuilder(ValidatorInterface::class)->getMock(); + $this->validator = $this->createMock(ValidatorInterface::class); $metadata = $this->getMockBuilder(ClassMetadata::class)->setConstructorArgs([''])->setMethods(['addPropertyConstraint'])->getMock(); $this->validator->expects($this->any())->method('getMetadataFor')->will($this->returnValue($metadata)); $this->validator->expects($this->any())->method('validate')->will($this->returnValue(new ConstraintViolationList())); diff --git a/src/Symfony/Component/Form/Test/TypeTestCase.php b/src/Symfony/Component/Form/Test/TypeTestCase.php index 51e6b85c6eca..43a74c7d4ef3 100644 --- a/src/Symfony/Component/Form/Test/TypeTestCase.php +++ b/src/Symfony/Component/Form/Test/TypeTestCase.php @@ -33,7 +33,7 @@ private function doSetUp() { parent::setUp(); - $this->dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); $this->builder = new FormBuilder('', null, $this->dispatcher, $this->factory); } diff --git a/src/Symfony/Component/Form/Tests/AbstractFormTest.php b/src/Symfony/Component/Form/Tests/AbstractFormTest.php index a893861680b7..78cb98548589 100644 --- a/src/Symfony/Component/Form/Tests/AbstractFormTest.php +++ b/src/Symfony/Component/Form/Tests/AbstractFormTest.php @@ -15,8 +15,12 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\Form\DataMapperInterface; +use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\FormBuilder; +use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\FormInterface; +use Symfony\Component\Form\FormValidatorInterface; abstract class AbstractFormTest extends TestCase { @@ -26,7 +30,7 @@ abstract class AbstractFormTest extends TestCase protected $dispatcher; /** - * @var \Symfony\Component\Form\FormFactoryInterface + * @var FormFactoryInterface */ protected $factory; @@ -38,7 +42,7 @@ abstract class AbstractFormTest extends TestCase protected function setUp(): void { $this->dispatcher = new EventDispatcher(); - $this->factory = $this->getMockBuilder(\Symfony\Component\Form\FormFactoryInterface::class)->getMock(); + $this->factory = $this->createMock(FormFactoryInterface::class); $this->form = $this->createForm(); } @@ -58,16 +62,16 @@ protected function getBuilder(?string $name = 'name', EventDispatcherInterface $ protected function getDataMapper(): MockObject { - return $this->getMockBuilder(\Symfony\Component\Form\DataMapperInterface::class)->getMock(); + return $this->createMock(DataMapperInterface::class); } protected function getDataTransformer(): MockObject { - return $this->getMockBuilder(\Symfony\Component\Form\DataTransformerInterface::class)->getMock(); + return $this->createMock(DataTransformerInterface::class); } protected function getFormValidator(): MockObject { - return $this->getMockBuilder(\Symfony\Component\Form\FormValidatorInterface::class)->getMock(); + return $this->createMock(FormValidatorInterface::class); } } diff --git a/src/Symfony/Component/Form/Tests/AbstractLayoutTest.php b/src/Symfony/Component/Form/Tests/AbstractLayoutTest.php index fc736eb7a371..52ef5360bc67 100644 --- a/src/Symfony/Component/Form/Tests/AbstractLayoutTest.php +++ b/src/Symfony/Component/Form/Tests/AbstractLayoutTest.php @@ -18,6 +18,7 @@ use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormView; use Symfony\Component\Form\Test\FormIntegrationTestCase; +use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; abstract class AbstractLayoutTest extends FormIntegrationTestCase { @@ -34,7 +35,7 @@ protected function setUp(): void \Locale::setDefault('en'); - $this->csrfTokenManager = $this->getMockBuilder(\Symfony\Component\Security\Csrf\CsrfTokenManagerInterface::class)->getMock(); + $this->csrfTokenManager = $this->createMock(CsrfTokenManagerInterface::class); parent::setUp(); } diff --git a/src/Symfony/Component/Form/Tests/AbstractRequestHandlerTest.php b/src/Symfony/Component/Form/Tests/AbstractRequestHandlerTest.php index 5feeef083a23..4d768f554a17 100644 --- a/src/Symfony/Component/Form/Tests/AbstractRequestHandlerTest.php +++ b/src/Symfony/Component/Form/Tests/AbstractRequestHandlerTest.php @@ -18,8 +18,10 @@ use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormFactory; +use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\Forms; use Symfony\Component\Form\RequestHandlerInterface; +use Symfony\Component\Form\Util\ServerParams; /** * @author Bernhard Schussek @@ -42,7 +44,7 @@ abstract class AbstractRequestHandlerTest extends TestCase protected function setUp(): void { - $this->serverParams = $this->getMockBuilder(\Symfony\Component\Form\Util\ServerParams::class)->setMethods(['getNormalizedIniPostMaxSize', 'getContentLength'])->getMock(); + $this->serverParams = $this->getMockBuilder(ServerParams::class)->setMethods(['getNormalizedIniPostMaxSize', 'getContentLength'])->getMock(); $this->requestHandler = $this->getRequestHandler(); $this->factory = Forms::createFormFactoryBuilder()->getFormFactory(); $this->request = null; @@ -405,7 +407,7 @@ protected function createForm($name, $method = null, $compound = false) protected function createBuilder($name, $compound = false, array $options = []) { - $builder = new FormBuilder($name, null, new EventDispatcher(), $this->getMockBuilder(\Symfony\Component\Form\FormFactoryInterface::class)->getMock(), $options); + $builder = new FormBuilder($name, null, new EventDispatcher(), $this->createMock(FormFactoryInterface::class), $options); $builder->setCompound($compound); if ($compound) { diff --git a/src/Symfony/Component/Form/Tests/AbstractTypeExtensionTest.php b/src/Symfony/Component/Form/Tests/AbstractTypeExtensionTest.php index 87ebad542acd..24e6702afa7c 100644 --- a/src/Symfony/Component/Form/Tests/AbstractTypeExtensionTest.php +++ b/src/Symfony/Component/Form/Tests/AbstractTypeExtensionTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Form\Extension\Core\Type\DateTimeType; class AbstractTypeExtensionTest extends TestCase @@ -21,7 +22,7 @@ class AbstractTypeExtensionTest extends TestCase */ public function testImplementingNeitherGetExtendedTypeNorExtendsTypeThrowsException() { - $this->expectException(\Symfony\Component\Form\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('You need to implement the static getExtendedTypes() method when implementing the "Symfony\Component\Form\FormTypeExtensionInterface" in "Symfony\Component\Form\Tests\TypeExtensionWithoutExtendedTypes".'); $extension = new TypeExtensionWithoutExtendedTypes(); $extension->getExtendedType(); diff --git a/src/Symfony/Component/Form/Tests/ButtonTest.php b/src/Symfony/Component/Form/Tests/ButtonTest.php index bd132f45199f..e665eca5f804 100644 --- a/src/Symfony/Component/Form/Tests/ButtonTest.php +++ b/src/Symfony/Component/Form/Tests/ButtonTest.php @@ -12,8 +12,11 @@ namespace Symfony\Component\Form\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Form\ButtonBuilder; +use Symfony\Component\Form\Exception\AlreadySubmittedException; use Symfony\Component\Form\FormBuilder; +use Symfony\Component\Form\FormFactoryInterface; /** * @author Bernhard Schussek @@ -26,13 +29,13 @@ class ButtonTest extends TestCase protected function setUp(): void { - $this->dispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class)->getMock(); - $this->factory = $this->getMockBuilder(\Symfony\Component\Form\FormFactoryInterface::class)->getMock(); + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); + $this->factory = $this->createMock(FormFactoryInterface::class); } public function testSetParentOnSubmittedButton() { - $this->expectException(\Symfony\Component\Form\Exception\AlreadySubmittedException::class); + $this->expectException(AlreadySubmittedException::class); $button = $this->getButtonBuilder('button') ->getForm() ; diff --git a/src/Symfony/Component/Form/Tests/ChoiceList/Factory/CachingFactoryDecoratorTest.php b/src/Symfony/Component/Form/Tests/ChoiceList/Factory/CachingFactoryDecoratorTest.php index 3cdd93f47945..a7e564475d9c 100644 --- a/src/Symfony/Component/Form/Tests/ChoiceList/Factory/CachingFactoryDecoratorTest.php +++ b/src/Symfony/Component/Form/Tests/ChoiceList/Factory/CachingFactoryDecoratorTest.php @@ -14,7 +14,10 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\Form\ChoiceList\ArrayChoiceList; +use Symfony\Component\Form\ChoiceList\ChoiceListInterface; use Symfony\Component\Form\ChoiceList\Factory\CachingFactoryDecorator; +use Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface; +use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface; use Symfony\Component\Form\ChoiceList\View\ChoiceListView; /** @@ -34,7 +37,7 @@ class CachingFactoryDecoratorTest extends TestCase protected function setUp(): void { - $this->decoratedFactory = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface::class)->getMock(); + $this->decoratedFactory = $this->createMock(ChoiceListFactoryInterface::class); $this->factory = new CachingFactoryDecorator($this->decoratedFactory); } @@ -163,7 +166,7 @@ public function testCreateFromChoicesDifferentValueClosure() public function testCreateFromLoaderSameLoader() { - $loader = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface::class)->getMock(); + $loader = $this->createMock(ChoiceLoaderInterface::class); $list = new ArrayChoiceList([]); $this->decoratedFactory->expects($this->once()) @@ -177,8 +180,8 @@ public function testCreateFromLoaderSameLoader() public function testCreateFromLoaderDifferentLoader() { - $loader1 = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface::class)->getMock(); - $loader2 = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface::class)->getMock(); + $loader1 = $this->createMock(ChoiceLoaderInterface::class); + $loader2 = $this->createMock(ChoiceLoaderInterface::class); $list1 = new ArrayChoiceList([]); $list2 = new ArrayChoiceList([]); @@ -196,7 +199,7 @@ public function testCreateFromLoaderDifferentLoader() public function testCreateFromLoaderSameValueClosure() { - $loader = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface::class)->getMock(); + $loader = $this->createMock(ChoiceLoaderInterface::class); $list = new ArrayChoiceList([]); $closure = function () {}; @@ -211,7 +214,7 @@ public function testCreateFromLoaderSameValueClosure() public function testCreateFromLoaderDifferentValueClosure() { - $loader = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface::class)->getMock(); + $loader = $this->createMock(ChoiceLoaderInterface::class); $list1 = new ArrayChoiceList([]); $list2 = new ArrayChoiceList([]); $closure1 = function () {}; @@ -232,7 +235,7 @@ public function testCreateFromLoaderDifferentValueClosure() public function testCreateViewSamePreferredChoices() { $preferred = ['a']; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view = new ChoiceListView(); $this->decoratedFactory->expects($this->once()) @@ -248,7 +251,7 @@ public function testCreateViewDifferentPreferredChoices() { $preferred1 = ['a']; $preferred2 = ['b']; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view1 = new ChoiceListView(); $view2 = new ChoiceListView(); @@ -267,7 +270,7 @@ public function testCreateViewDifferentPreferredChoices() public function testCreateViewSamePreferredChoicesClosure() { $preferred = function () {}; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view = new ChoiceListView(); $this->decoratedFactory->expects($this->once()) @@ -283,7 +286,7 @@ public function testCreateViewDifferentPreferredChoicesClosure() { $preferred1 = function () {}; $preferred2 = function () {}; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view1 = new ChoiceListView(); $view2 = new ChoiceListView(); @@ -302,7 +305,7 @@ public function testCreateViewDifferentPreferredChoicesClosure() public function testCreateViewSameLabelClosure() { $labels = function () {}; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view = new ChoiceListView(); $this->decoratedFactory->expects($this->once()) @@ -318,7 +321,7 @@ public function testCreateViewDifferentLabelClosure() { $labels1 = function () {}; $labels2 = function () {}; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view1 = new ChoiceListView(); $view2 = new ChoiceListView(); @@ -337,7 +340,7 @@ public function testCreateViewDifferentLabelClosure() public function testCreateViewSameIndexClosure() { $index = function () {}; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view = new ChoiceListView(); $this->decoratedFactory->expects($this->once()) @@ -353,7 +356,7 @@ public function testCreateViewDifferentIndexClosure() { $index1 = function () {}; $index2 = function () {}; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view1 = new ChoiceListView(); $view2 = new ChoiceListView(); @@ -372,7 +375,7 @@ public function testCreateViewDifferentIndexClosure() public function testCreateViewSameGroupByClosure() { $groupBy = function () {}; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view = new ChoiceListView(); $this->decoratedFactory->expects($this->once()) @@ -388,7 +391,7 @@ public function testCreateViewDifferentGroupByClosure() { $groupBy1 = function () {}; $groupBy2 = function () {}; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view1 = new ChoiceListView(); $view2 = new ChoiceListView(); @@ -407,7 +410,7 @@ public function testCreateViewDifferentGroupByClosure() public function testCreateViewSameAttributes() { $attr = ['class' => 'foobar']; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view = new ChoiceListView(); $this->decoratedFactory->expects($this->once()) @@ -423,7 +426,7 @@ public function testCreateViewDifferentAttributes() { $attr1 = ['class' => 'foobar1']; $attr2 = ['class' => 'foobar2']; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view1 = new ChoiceListView(); $view2 = new ChoiceListView(); @@ -442,7 +445,7 @@ public function testCreateViewDifferentAttributes() public function testCreateViewSameAttributesClosure() { $attr = function () {}; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view = new ChoiceListView(); $this->decoratedFactory->expects($this->once()) @@ -458,7 +461,7 @@ public function testCreateViewDifferentAttributesClosure() { $attr1 = function () {}; $attr2 = function () {}; - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $view1 = new ChoiceListView(); $view2 = new ChoiceListView(); diff --git a/src/Symfony/Component/Form/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php b/src/Symfony/Component/Form/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php index a70c84bd4b18..18cf4daa0cb3 100644 --- a/src/Symfony/Component/Form/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php +++ b/src/Symfony/Component/Form/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php @@ -16,6 +16,7 @@ use Symfony\Component\Form\ChoiceList\ChoiceListInterface; use Symfony\Component\Form\ChoiceList\Factory\DefaultChoiceListFactory; use Symfony\Component\Form\ChoiceList\LazyChoiceList; +use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface; use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView; use Symfony\Component\Form\ChoiceList\View\ChoiceListView; use Symfony\Component\Form\ChoiceList\View\ChoiceView; @@ -193,7 +194,7 @@ function ($object) { return $object->value; } public function testCreateFromLoader() { - $loader = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface::class)->getMock(); + $loader = $this->createMock(ChoiceLoaderInterface::class); $list = $this->factory->createListFromLoader($loader); @@ -202,7 +203,7 @@ public function testCreateFromLoader() public function testCreateFromLoaderWithValues() { - $loader = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface::class)->getMock(); + $loader = $this->createMock(ChoiceLoaderInterface::class); $value = function () {}; $list = $this->factory->createListFromLoader($loader, $value); diff --git a/src/Symfony/Component/Form/Tests/ChoiceList/Factory/PropertyAccessDecoratorTest.php b/src/Symfony/Component/Form/Tests/ChoiceList/Factory/PropertyAccessDecoratorTest.php index f62a0dcb1360..3d253edddf23 100644 --- a/src/Symfony/Component/Form/Tests/ChoiceList/Factory/PropertyAccessDecoratorTest.php +++ b/src/Symfony/Component/Form/Tests/ChoiceList/Factory/PropertyAccessDecoratorTest.php @@ -14,7 +14,10 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\Form\ChoiceList\ArrayChoiceList; +use Symfony\Component\Form\ChoiceList\ChoiceListInterface; +use Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface; use Symfony\Component\Form\ChoiceList\Factory\PropertyAccessDecorator; +use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface; use Symfony\Component\Form\ChoiceList\View\ChoiceListView; use Symfony\Component\PropertyAccess\PropertyPath; @@ -35,7 +38,7 @@ class PropertyAccessDecoratorTest extends TestCase protected function setUp(): void { - $this->decoratedFactory = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface::class)->getMock(); + $this->decoratedFactory = $this->createMock(ChoiceListFactoryInterface::class); $this->factory = new PropertyAccessDecorator($this->decoratedFactory); } @@ -69,7 +72,7 @@ public function testCreateFromChoicesPropertyPathInstance() public function testCreateFromLoaderPropertyPath() { - $loader = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface::class)->getMock(); + $loader = $this->createMock(ChoiceLoaderInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createListFromLoader') @@ -99,7 +102,7 @@ public function testCreateFromChoicesAssumeNullIfValuePropertyPathUnreadable() // https://github.com/symfony/symfony/issues/5494 public function testCreateFromChoiceLoaderAssumeNullIfValuePropertyPathUnreadable() { - $loader = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface::class)->getMock(); + $loader = $this->createMock(ChoiceLoaderInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createListFromLoader') @@ -113,7 +116,7 @@ public function testCreateFromChoiceLoaderAssumeNullIfValuePropertyPathUnreadabl public function testCreateFromLoaderPropertyPathInstance() { - $loader = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface::class)->getMock(); + $loader = $this->createMock(ChoiceLoaderInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createListFromLoader') @@ -127,7 +130,7 @@ public function testCreateFromLoaderPropertyPathInstance() public function testCreateViewPreferredChoicesAsPropertyPath() { - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createView') @@ -141,7 +144,7 @@ public function testCreateViewPreferredChoicesAsPropertyPath() public function testCreateViewPreferredChoicesAsPropertyPathInstance() { - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createView') @@ -156,7 +159,7 @@ public function testCreateViewPreferredChoicesAsPropertyPathInstance() // https://github.com/symfony/symfony/issues/5494 public function testCreateViewAssumeNullIfPreferredChoicesPropertyPathUnreadable() { - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createView') @@ -170,7 +173,7 @@ public function testCreateViewAssumeNullIfPreferredChoicesPropertyPathUnreadable public function testCreateViewLabelsAsPropertyPath() { - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createView') @@ -184,7 +187,7 @@ public function testCreateViewLabelsAsPropertyPath() public function testCreateViewLabelsAsPropertyPathInstance() { - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createView') @@ -198,7 +201,7 @@ public function testCreateViewLabelsAsPropertyPathInstance() public function testCreateViewIndicesAsPropertyPath() { - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createView') @@ -212,7 +215,7 @@ public function testCreateViewIndicesAsPropertyPath() public function testCreateViewIndicesAsPropertyPathInstance() { - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createView') @@ -226,7 +229,7 @@ public function testCreateViewIndicesAsPropertyPathInstance() public function testCreateViewGroupsAsPropertyPath() { - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createView') @@ -240,7 +243,7 @@ public function testCreateViewGroupsAsPropertyPath() public function testCreateViewGroupsAsPropertyPathInstance() { - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createView') @@ -255,7 +258,7 @@ public function testCreateViewGroupsAsPropertyPathInstance() // https://github.com/symfony/symfony/issues/5494 public function testCreateViewAssumeNullIfGroupsPropertyPathUnreadable() { - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createView') @@ -269,7 +272,7 @@ public function testCreateViewAssumeNullIfGroupsPropertyPathUnreadable() public function testCreateViewAttrAsPropertyPath() { - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createView') @@ -283,7 +286,7 @@ public function testCreateViewAttrAsPropertyPath() public function testCreateViewAttrAsPropertyPathInstance() { - $list = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); + $list = $this->createMock(ChoiceListInterface::class); $this->decoratedFactory->expects($this->once()) ->method('createView') diff --git a/src/Symfony/Component/Form/Tests/ChoiceList/LazyChoiceListTest.php b/src/Symfony/Component/Form/Tests/ChoiceList/LazyChoiceListTest.php index 7d6ed23e2a63..4bcb989f041b 100644 --- a/src/Symfony/Component/Form/Tests/ChoiceList/LazyChoiceListTest.php +++ b/src/Symfony/Component/Form/Tests/ChoiceList/LazyChoiceListTest.php @@ -13,7 +13,9 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\ChoiceList\ChoiceListInterface; use Symfony\Component\Form\ChoiceList\LazyChoiceList; +use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface; /** * @author Bernhard Schussek @@ -39,8 +41,8 @@ class LazyChoiceListTest extends TestCase protected function setUp(): void { - $this->loadedList = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\ChoiceListInterface::class)->getMock(); - $this->loader = $this->getMockBuilder(\Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface::class)->getMock(); + $this->loadedList = $this->createMock(ChoiceListInterface::class); + $this->loader = $this->createMock(ChoiceLoaderInterface::class); $this->value = function () {}; $this->list = new LazyChoiceList($this->loader, $this->value); } diff --git a/src/Symfony/Component/Form/Tests/CompoundFormTest.php b/src/Symfony/Component/Form/Tests/CompoundFormTest.php index c5953dd3f94b..a6fd1a1e93c7 100644 --- a/src/Symfony/Component/Form/Tests/CompoundFormTest.php +++ b/src/Symfony/Component/Form/Tests/CompoundFormTest.php @@ -12,16 +12,22 @@ namespace Symfony\Component\Form\Tests; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Form\Exception\AlreadySubmittedException; use Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper; use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler; +use Symfony\Component\Form\Form; use Symfony\Component\Form\FormError; +use Symfony\Component\Form\FormErrorIterator; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\Forms; use Symfony\Component\Form\FormView; +use Symfony\Component\Form\ResolvedFormTypeInterface; +use Symfony\Component\Form\SubmitButton; use Symfony\Component\Form\SubmitButtonBuilder; use Symfony\Component\Form\Tests\Fixtures\FixedDataTransformer; +use Symfony\Component\Form\Util\InheritDataAwareIterator; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; @@ -272,7 +278,7 @@ public function testAddUsingNameButNoTypeAndOptions() public function testAddThrowsExceptionIfAlreadySubmitted() { - $this->expectException(\Symfony\Component\Form\Exception\AlreadySubmittedException::class); + $this->expectException(AlreadySubmittedException::class); $this->form->submit([]); $this->form->add($this->getBuilder('foo')->getForm()); } @@ -289,7 +295,7 @@ public function testRemove() public function testRemoveThrowsExceptionIfAlreadySubmitted() { - $this->expectException(\Symfony\Component\Form\Exception\AlreadySubmittedException::class); + $this->expectException(AlreadySubmittedException::class); $this->form->add($this->getBuilder('foo')->setCompound(false)->getForm()); $this->form->submit(['foo' => 'bar']); $this->form->remove('foo'); @@ -350,7 +356,7 @@ public function testAddMapsViewDataToFormIfInitialized() ->method('mapDataToForms') ->with('bar', $this->isInstanceOf(\RecursiveIteratorIterator::class)) ->willReturnCallback(function ($data, \RecursiveIteratorIterator $iterator) use ($child) { - $this->assertInstanceOf(\Symfony\Component\Form\Util\InheritDataAwareIterator::class, $iterator->getInnerIterator()); + $this->assertInstanceOf(InheritDataAwareIterator::class, $iterator->getInnerIterator()); $this->assertSame([$child->getName() => $child], iterator_to_array($iterator)); }); @@ -440,7 +446,7 @@ public function testSetDataMapsViewDataToChildren() ->method('mapDataToForms') ->with('bar', $this->isInstanceOf(\RecursiveIteratorIterator::class)) ->willReturnCallback(function ($data, \RecursiveIteratorIterator $iterator) use ($child1, $child2) { - $this->assertInstanceOf(\Symfony\Component\Form\Util\InheritDataAwareIterator::class, $iterator->getInnerIterator()); + $this->assertInstanceOf(InheritDataAwareIterator::class, $iterator->getInnerIterator()); $this->assertSame(['firstName' => $child1, 'lastName' => $child2], iterator_to_array($iterator)); }); @@ -515,7 +521,7 @@ public function testSubmitMapsSubmittedChildrenOntoExistingViewData() ->method('mapFormsToData') ->with($this->isInstanceOf(\RecursiveIteratorIterator::class), 'bar') ->willReturnCallback(function (\RecursiveIteratorIterator $iterator) use ($child1, $child2) { - $this->assertInstanceOf(\Symfony\Component\Form\Util\InheritDataAwareIterator::class, $iterator->getInnerIterator()); + $this->assertInstanceOf(InheritDataAwareIterator::class, $iterator->getInnerIterator()); $this->assertSame(['firstName' => $child1, 'lastName' => $child2], iterator_to_array($iterator)); $this->assertEquals('Bernhard', $child1->getData()); $this->assertEquals('Schussek', $child2->getData()); @@ -587,7 +593,7 @@ public function testSubmitMapsSubmittedChildrenOntoEmptyData() ->method('mapFormsToData') ->with($this->isInstanceOf(\RecursiveIteratorIterator::class), $object) ->willReturnCallback(function (\RecursiveIteratorIterator $iterator) use ($child) { - $this->assertInstanceOf(\Symfony\Component\Form\Util\InheritDataAwareIterator::class, $iterator->getInnerIterator()); + $this->assertInstanceOf(InheritDataAwareIterator::class, $iterator->getInnerIterator()); $this->assertSame(['name' => $child], iterator_to_array($iterator)); }); @@ -887,7 +893,7 @@ public function testGetErrorsDeepRecursive() $this->assertSame($error1, $errorsAsArray[0]); $this->assertSame($error2, $errorsAsArray[1]); - $this->assertInstanceOf(\Symfony\Component\Form\FormErrorIterator::class, $errorsAsArray[2]); + $this->assertInstanceOf(FormErrorIterator::class, $errorsAsArray[2]); $nestedErrorsAsArray = iterator_to_array($errorsAsArray[2]); @@ -940,9 +946,9 @@ public function testClearErrorsDeep() // Basic cases are covered in SimpleFormTest public function testCreateViewWithChildren() { - $type = $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormTypeInterface::class)->getMock(); - $type1 = $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormTypeInterface::class)->getMock(); - $type2 = $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormTypeInterface::class)->getMock(); + $type = $this->createMock(ResolvedFormTypeInterface::class); + $type1 = $this->createMock(ResolvedFormTypeInterface::class); + $type2 = $this->createMock(ResolvedFormTypeInterface::class); $options = ['a' => 'Foo', 'b' => 'Bar']; $field1 = $this->getBuilder('foo') ->setType($type1) @@ -996,7 +1002,7 @@ public function testNoClickedButtonBeforeSubmission() public function testNoClickedButton() { - $button = $this->getMockBuilder(\Symfony\Component\Form\SubmitButton::class) + $button = $this->getMockBuilder(SubmitButton::class) ->setConstructorArgs([new SubmitButtonBuilder('submit')]) ->setMethods(['isClicked']) ->getMock(); @@ -1018,7 +1024,7 @@ public function testNoClickedButton() public function testClickedButton() { - $button = $this->getMockBuilder(\Symfony\Component\Form\SubmitButton::class) + $button = $this->getMockBuilder(SubmitButton::class) ->setConstructorArgs([new SubmitButtonBuilder('submit')]) ->setMethods(['isClicked']) ->getMock(); @@ -1037,7 +1043,7 @@ public function testClickedButtonFromNestedForm() { $button = $this->getBuilder('submit')->getForm(); - $nestedForm = $this->getMockBuilder(\Symfony\Component\Form\Form::class) + $nestedForm = $this->getMockBuilder(Form::class) ->setConstructorArgs([$this->getBuilder('nested')]) ->setMethods(['getClickedButton']) ->getMock(); @@ -1056,7 +1062,7 @@ public function testClickedButtonFromParentForm() { $button = $this->getBuilder('submit')->getForm(); - $parentForm = $this->getMockBuilder(\Symfony\Component\Form\Form::class) + $parentForm = $this->getMockBuilder(Form::class) ->setConstructorArgs([$this->getBuilder('parent')]) ->setMethods(['getClickedButton']) ->getMock(); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.php index 105df0514b7b..b82a3a380212 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\ArrayToPartsTransformer; class ArrayToPartsTransformerTest extends TestCase @@ -70,7 +71,7 @@ public function testTransformEmpty() public function testTransformRequiresArray() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->transformer->transform('12345'); } @@ -123,7 +124,7 @@ public function testReverseTransformCompletelyNull() public function testReverseTransformPartiallyNull() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $input = [ 'first' => [ 'a' => '1', @@ -138,7 +139,7 @@ public function testReverseTransformPartiallyNull() public function testReverseTransformRequiresArray() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->transformer->reverseTransform('12345'); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTest.php index 5aa4a865f494..f6d4226e5bef 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTest.php @@ -12,20 +12,22 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\InvalidArgumentException; +use Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer; class BaseDateTimeTransformerTest extends TestCase { public function testConstructFailsIfInputTimezoneIsInvalid() { - $this->expectException(\Symfony\Component\Form\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('this_timezone_does_not_exist'); - $this->getMockBuilder(\Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer::class)->setConstructorArgs(['this_timezone_does_not_exist'])->getMock(); + $this->getMockBuilder(BaseDateTimeTransformer::class)->setConstructorArgs(['this_timezone_does_not_exist'])->getMock(); } public function testConstructFailsIfOutputTimezoneIsInvalid() { - $this->expectException(\Symfony\Component\Form\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('that_timezone_does_not_exist'); - $this->getMockBuilder(\Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer::class)->setConstructorArgs([null, 'that_timezone_does_not_exist'])->getMock(); + $this->getMockBuilder(BaseDateTimeTransformer::class)->setConstructorArgs([null, 'that_timezone_does_not_exist'])->getMock(); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.php index 0252f422599a..98d58c612a34 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\InvalidArgumentException; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\BooleanToStringTransformer; class BooleanToStringTransformerTest extends TestCase @@ -47,13 +49,13 @@ public function testTransformAcceptsNull() public function testTransformFailsIfString() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->transformer->transform('1'); } public function testReverseTransformFailsIfInteger() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->transformer->reverseTransform(1); } @@ -75,7 +77,7 @@ public function testCustomFalseValues() public function testTrueValueContainedInFalseValues() { - $this->expectException(\Symfony\Component\Form\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); new BooleanToStringTransformer('0', [null, '0']); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php index 65089b0fef2a..7711fcb7f059 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Form\ChoiceList\ArrayChoiceList; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\ChoiceToValueTransformer; class ChoiceToValueTransformerTest extends TestCase @@ -91,7 +92,7 @@ public function reverseTransformExpectsStringOrNullProvider() */ public function testReverseTransformExpectsStringOrNull($value) { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->transformer->reverseTransform($value); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php index a330273cad49..d0911673dd7d 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Form\ChoiceList\ArrayChoiceList; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\ChoicesToValuesTransformer; class ChoicesToValuesTransformerTest extends TestCase @@ -55,7 +56,7 @@ public function testTransformNull() public function testTransformExpectsArray() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->transformer->transform('foobar'); } @@ -81,7 +82,7 @@ public function testReverseTransformNull() public function testReverseTransformExpectsArray() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->transformer->reverseTransform('foobar'); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DataTransformerChainTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DataTransformerChainTest.php index f8038b0c20df..307667b1f75f 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DataTransformerChainTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DataTransformerChainTest.php @@ -12,18 +12,19 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\Extension\Core\DataTransformer\DataTransformerChain; class DataTransformerChainTest extends TestCase { public function testTransform() { - $transformer1 = $this->getMockBuilder(\Symfony\Component\Form\DataTransformerInterface::class)->getMock(); + $transformer1 = $this->createMock(DataTransformerInterface::class); $transformer1->expects($this->once()) ->method('transform') ->with($this->identicalTo('foo')) ->willReturn('bar'); - $transformer2 = $this->getMockBuilder(\Symfony\Component\Form\DataTransformerInterface::class)->getMock(); + $transformer2 = $this->createMock(DataTransformerInterface::class); $transformer2->expects($this->once()) ->method('transform') ->with($this->identicalTo('bar')) @@ -36,12 +37,12 @@ public function testTransform() public function testReverseTransform() { - $transformer2 = $this->getMockBuilder(\Symfony\Component\Form\DataTransformerInterface::class)->getMock(); + $transformer2 = $this->createMock(DataTransformerInterface::class); $transformer2->expects($this->once()) ->method('reverseTransform') ->with($this->identicalTo('foo')) ->willReturn('bar'); - $transformer1 = $this->getMockBuilder(\Symfony\Component\Form\DataTransformerInterface::class)->getMock(); + $transformer1 = $this->createMock(DataTransformerInterface::class); $transformer1->expects($this->once()) ->method('reverseTransform') ->with($this->identicalTo('bar')) diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformerTest.php index d73c7b99be5c..7aa18d924e5d 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeImmutableToDateTimeTransformer; class DateTimeImmutableToDateTimeTransformerTest extends TestCase @@ -54,7 +55,7 @@ public function testTransformEmpty() public function testTransformFail() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->expectExceptionMessage('Expected a \DateTimeImmutable.'); $transformer = new DateTimeImmutableToDateTimeTransformer(); $transformer->transform(new \DateTime()); @@ -82,7 +83,7 @@ public function testReverseTransformEmpty() public function testReverseTransformFail() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->expectExceptionMessage('Expected a \DateTime.'); $transformer = new DateTimeImmutableToDateTimeTransformer(); $transformer->reverseTransform(new \DateTimeImmutable()); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.php index 0a8b17ae9e38..3ebfb9d1b51f 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToArrayTransformer; class DateTimeToArrayTransformerTest extends TestCase @@ -139,7 +140,7 @@ public function testTransformDateTimeImmutable() public function testTransformRequiresDateTime() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform('12345'); } @@ -211,7 +212,7 @@ public function testReverseTransformCompletelyEmptySubsetOfFields() public function testReverseTransformPartiallyEmptyYear() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'month' => '2', @@ -224,7 +225,7 @@ public function testReverseTransformPartiallyEmptyYear() public function testReverseTransformPartiallyEmptyMonth() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -237,7 +238,7 @@ public function testReverseTransformPartiallyEmptyMonth() public function testReverseTransformPartiallyEmptyDay() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -250,7 +251,7 @@ public function testReverseTransformPartiallyEmptyDay() public function testReverseTransformPartiallyEmptyHour() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -263,7 +264,7 @@ public function testReverseTransformPartiallyEmptyHour() public function testReverseTransformPartiallyEmptyMinute() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -276,7 +277,7 @@ public function testReverseTransformPartiallyEmptyMinute() public function testReverseTransformPartiallyEmptySecond() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -334,14 +335,14 @@ public function testReverseTransformToDifferentTimezone() public function testReverseTransformRequiresArray() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform('12345'); } public function testReverseTransformWithNegativeYear() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '-1', @@ -355,7 +356,7 @@ public function testReverseTransformWithNegativeYear() public function testReverseTransformWithNegativeMonth() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -369,7 +370,7 @@ public function testReverseTransformWithNegativeMonth() public function testReverseTransformWithNegativeDay() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -383,7 +384,7 @@ public function testReverseTransformWithNegativeDay() public function testReverseTransformWithNegativeHour() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -397,7 +398,7 @@ public function testReverseTransformWithNegativeHour() public function testReverseTransformWithNegativeMinute() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -411,7 +412,7 @@ public function testReverseTransformWithNegativeMinute() public function testReverseTransformWithNegativeSecond() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -425,7 +426,7 @@ public function testReverseTransformWithNegativeSecond() public function testReverseTransformWithInvalidMonth() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -439,7 +440,7 @@ public function testReverseTransformWithInvalidMonth() public function testReverseTransformWithInvalidDay() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -453,7 +454,7 @@ public function testReverseTransformWithInvalidDay() public function testReverseTransformWithStringDay() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -467,7 +468,7 @@ public function testReverseTransformWithStringDay() public function testReverseTransformWithStringMonth() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -481,7 +482,7 @@ public function testReverseTransformWithStringMonth() public function testReverseTransformWithStringYear() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => 'bazinga', @@ -495,7 +496,7 @@ public function testReverseTransformWithStringYear() public function testReverseTransformWithEmptyStringHour() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -509,7 +510,7 @@ public function testReverseTransformWithEmptyStringHour() public function testReverseTransformWithEmptyStringMinute() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -523,7 +524,7 @@ public function testReverseTransformWithEmptyStringMinute() public function testReverseTransformWithEmptyStringSecond() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php index 97bda01756a8..2e4b4ba7e696 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToHtml5LocalDateTimeTransformer; use Symfony\Component\Form\Tests\Extension\Core\DataTransformer\Traits\DateTimeEqualsTrait; @@ -73,7 +74,7 @@ public function testTransformDateTimeImmutable($fromTz, $toTz, $from, $to) public function testTransformRequiresValidDateTime() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToHtml5LocalDateTimeTransformer(); $transformer->transform('2010-01-01'); } @@ -94,14 +95,14 @@ public function testReverseTransform($toTz, $fromTz, $to, $from) public function testReverseTransformRequiresString() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToHtml5LocalDateTimeTransformer(); $transformer->reverseTransform(12345); } public function testReverseTransformWithNonExistingDate() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToHtml5LocalDateTimeTransformer('UTC', 'UTC'); $transformer->reverseTransform('2010-04-31T04:05'); @@ -109,7 +110,7 @@ public function testReverseTransformWithNonExistingDate() public function testReverseTransformExpectsValidDateString() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToHtml5LocalDateTimeTransformer('UTC', 'UTC'); $transformer->reverseTransform('2010-2010-2010'); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php index 68518baf9566..e2aa4748d8cf 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToLocalizedStringTransformer; use Symfony\Component\Form\Tests\Extension\Core\DataTransformer\Traits\DateTimeEqualsTrait; use Symfony\Component\Intl\Util\IntlTestHelper; @@ -180,7 +181,7 @@ public function testTransformDateTimeImmutableTimezones() public function testTransformRequiresValidDateTime() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToLocalizedStringTransformer(); $transformer->transform('2010-01-01'); } @@ -288,21 +289,21 @@ public function testReverseTransformEmpty() public function testReverseTransformRequiresString() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToLocalizedStringTransformer(); $transformer->reverseTransform(12345); } public function testReverseTransformWrapsIntlErrors() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToLocalizedStringTransformer(); $transformer->reverseTransform('12345'); } public function testReverseTransformWithNonExistingDate() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC', \IntlDateFormatter::SHORT); $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('31.04.10 04:05')); @@ -310,21 +311,21 @@ public function testReverseTransformWithNonExistingDate() public function testReverseTransformOutOfTimestampRange() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC'); $transformer->reverseTransform('1789-07-14'); } public function testReverseTransformFiveDigitYears() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC', null, null, \IntlDateFormatter::GREGORIAN, 'yyyy-MM-dd'); $transformer->reverseTransform('20107-03-21'); } public function testReverseTransformFiveDigitYearsWithTimestamp() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC', null, null, \IntlDateFormatter::GREGORIAN, 'yyyy-MM-dd HH:mm:ss'); $transformer->reverseTransform('20107-03-21 12:34:56'); } @@ -337,7 +338,7 @@ public function testReverseTransformWrapsIntlErrorsWithErrorLevel() $this->iniSet('intl.error_level', \E_WARNING); - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToLocalizedStringTransformer(); $transformer->reverseTransform('12345'); } @@ -350,7 +351,7 @@ public function testReverseTransformWrapsIntlErrorsWithExceptions() $this->iniSet('intl.use_exceptions', 1); - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToLocalizedStringTransformer(); $transformer->reverseTransform('12345'); } @@ -364,7 +365,7 @@ public function testReverseTransformWrapsIntlErrorsWithExceptionsAndErrorLevel() $this->iniSet('intl.use_exceptions', 1); $this->iniSet('intl.error_level', \E_WARNING); - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToLocalizedStringTransformer(); $transformer->reverseTransform('12345'); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php index d34e52ab38b1..0c28ac50951c 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToRfc3339Transformer; use Symfony\Component\Form\Tests\Extension\Core\DataTransformer\Traits\DateTimeEqualsTrait; @@ -86,7 +87,7 @@ public function testTransformDateTimeImmutable($fromTz, $toTz, $from, $to) public function testTransformRequiresValidDateTime() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToRfc3339Transformer(); $transformer->transform('2010-01-01'); } @@ -107,14 +108,14 @@ public function testReverseTransform($toTz, $fromTz, $to, $from) public function testReverseTransformRequiresString() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToRfc3339Transformer(); $transformer->reverseTransform(12345); } public function testReverseTransformWithNonExistingDate() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToRfc3339Transformer('UTC', 'UTC'); $transformer->reverseTransform('2010-04-31T04:05Z'); @@ -125,7 +126,7 @@ public function testReverseTransformWithNonExistingDate() */ public function testReverseTransformExpectsValidDateString($date) { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToRfc3339Transformer('UTC', 'UTC'); $transformer->reverseTransform($date); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToStringTransformerTest.php index ffd92d31f3bd..60d9d5a84e42 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToStringTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer; class DateTimeToStringTransformerTest extends TestCase @@ -111,7 +112,7 @@ public function testTransformExpectsDateTime() { $transformer = new DateTimeToStringTransformer(); - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer->transform('1234'); } @@ -150,7 +151,7 @@ public function testReverseTransformExpectsString() { $reverseTransformer = new DateTimeToStringTransformer(); - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $reverseTransformer->reverseTransform(1234); } @@ -159,7 +160,7 @@ public function testReverseTransformExpectsValidDateString() { $reverseTransformer = new DateTimeToStringTransformer(); - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $reverseTransformer->reverseTransform('2010-2010-2010'); } @@ -168,7 +169,7 @@ public function testReverseTransformWithNonExistingDate() { $reverseTransformer = new DateTimeToStringTransformer(); - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $reverseTransformer->reverseTransform('2010-04-31'); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToTimestampTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToTimestampTransformerTest.php index 0f5ff2fb7a32..b02be9a168b8 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToTimestampTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToTimestampTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToTimestampTransformer; class DateTimeToTimestampTransformerTest extends TestCase @@ -72,7 +73,7 @@ public function testTransformExpectsDateTime() { $transformer = new DateTimeToTimestampTransformer(); - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer->transform('1234'); } @@ -109,7 +110,7 @@ public function testReverseTransformExpectsValidTimestamp() { $reverseTransformer = new DateTimeToTimestampTransformer(); - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $reverseTransformer->reverseTransform('2010-2010-2010'); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeZoneToStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeZoneToStringTransformerTest.php index ed1df8717c67..cf51dcb0dc12 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeZoneToStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeZoneToStringTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeZoneToStringTransformer; class DateTimeZoneToStringTransformerTest extends TestCase @@ -40,13 +41,13 @@ public function testMultiple() public function testInvalidTimezone() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); (new DateTimeZoneToStringTransformer())->transform(1); } public function testUnknownTimezone() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); (new DateTimeZoneToStringTransformer(true))->reverseTransform(['Foo/Bar']); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php index a1375997575d..9a1774bc4bd0 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\IntegerToLocalizedStringTransformer; use Symfony\Component\Intl\Util\IntlTestHelper; @@ -232,7 +233,7 @@ public function testReverseTransformWithRoundingUsingLegacyConstructorSignature( public function testReverseTransformExpectsString() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new IntegerToLocalizedStringTransformer(); $transformer->reverseTransform(1); @@ -240,7 +241,7 @@ public function testReverseTransformExpectsString() public function testReverseTransformExpectsValidNumber() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new IntegerToLocalizedStringTransformer(); $transformer->reverseTransform('foo'); @@ -251,7 +252,7 @@ public function testReverseTransformExpectsValidNumber() */ public function testReverseTransformExpectsInteger($number, $locale) { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); IntlTestHelper::requireFullIntl($this, false); \Locale::setDefault($locale); @@ -271,7 +272,7 @@ public function floatNumberProvider() public function testReverseTransformDisallowsNaN() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new IntegerToLocalizedStringTransformer(); $transformer->reverseTransform('NaN'); @@ -279,7 +280,7 @@ public function testReverseTransformDisallowsNaN() public function testReverseTransformDisallowsNaN2() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new IntegerToLocalizedStringTransformer(); $transformer->reverseTransform('nan'); @@ -287,7 +288,7 @@ public function testReverseTransformDisallowsNaN2() public function testReverseTransformDisallowsInfinity() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new IntegerToLocalizedStringTransformer(); $transformer->reverseTransform('∞'); @@ -295,7 +296,7 @@ public function testReverseTransformDisallowsInfinity() public function testReverseTransformDisallowsNegativeInfinity() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new IntegerToLocalizedStringTransformer(); $transformer->reverseTransform('-∞'); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformerTest.php index 464c266e7b97..ca80a2103153 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\IntlTimeZoneToStringTransformer; /** @@ -43,13 +44,13 @@ public function testMultiple() public function testInvalidTimezone() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); (new IntlTimeZoneToStringTransformer())->transform(1); } public function testUnknownTimezone() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); (new IntlTimeZoneToStringTransformer(true))->reverseTransform(['Foo/Bar']); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php index 489f8457b81e..4bc43fc8dfce 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\MoneyToLocalizedStringTransformer; use Symfony\Component\Intl\Util\IntlTestHelper; @@ -45,7 +46,7 @@ public function testTransformExpectsNumeric() { $transformer = new MoneyToLocalizedStringTransformer(null, null, null, 100); - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer->transform('abcd'); } @@ -73,7 +74,7 @@ public function testReverseTransformExpectsString() { $transformer = new MoneyToLocalizedStringTransformer(null, null, null, 100); - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer->reverseTransform(12345); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php index e776ea34ebad..e4008e8d888f 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\NumberToLocalizedStringTransformer; use Symfony\Component\Intl\Util\IntlTestHelper; @@ -399,7 +400,7 @@ public function testDecimalSeparatorMayBeDotIfGroupingSeparatorIsNotDot() public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDot() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); // Since we test against "de_DE", we need the full implementation IntlTestHelper::requireFullIntl($this, '4.8.1.1'); @@ -412,7 +413,7 @@ public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDot() public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDotWithNoGroupSep() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); // Since we test against "de_DE", we need the full implementation IntlTestHelper::requireFullIntl($this, '4.8.1.1'); @@ -454,7 +455,7 @@ public function testDecimalSeparatorMayBeCommaIfGroupingSeparatorIsNotComma() public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsComma() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); IntlTestHelper::requireFullIntl($this, '4.8.1.1'); $transformer = new NumberToLocalizedStringTransformer(null, true); @@ -464,7 +465,7 @@ public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsComma() public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsCommaWithNoGroupSep() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); IntlTestHelper::requireFullIntl($this, '4.8.1.1'); $transformer = new NumberToLocalizedStringTransformer(null, true); @@ -482,7 +483,7 @@ public function testDecimalSeparatorMayBeCommaIfGroupingSeparatorIsCommaButNoGro public function testTransformExpectsNumeric() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new NumberToLocalizedStringTransformer(); $transformer->transform('foo'); @@ -490,7 +491,7 @@ public function testTransformExpectsNumeric() public function testReverseTransformExpectsString() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform(1); @@ -498,7 +499,7 @@ public function testReverseTransformExpectsString() public function testReverseTransformExpectsValidNumber() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform('foo'); @@ -511,7 +512,7 @@ public function testReverseTransformExpectsValidNumber() */ public function testReverseTransformDisallowsNaN($nan) { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform($nan); @@ -528,7 +529,7 @@ public function nanRepresentationProvider() public function testReverseTransformDisallowsInfinity() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform('∞'); @@ -536,7 +537,7 @@ public function testReverseTransformDisallowsInfinity() public function testReverseTransformDisallowsInfinity2() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform('∞,123'); @@ -544,7 +545,7 @@ public function testReverseTransformDisallowsInfinity2() public function testReverseTransformDisallowsNegativeInfinity() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform('-∞'); @@ -552,7 +553,7 @@ public function testReverseTransformDisallowsNegativeInfinity() public function testReverseTransformDisallowsLeadingExtraCharacters() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform('foo123'); @@ -560,7 +561,7 @@ public function testReverseTransformDisallowsLeadingExtraCharacters() public function testReverseTransformDisallowsCenteredExtraCharacters() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->expectExceptionMessage('The number contains unrecognized characters: "foo3"'); $transformer = new NumberToLocalizedStringTransformer(); @@ -569,7 +570,7 @@ public function testReverseTransformDisallowsCenteredExtraCharacters() public function testReverseTransformDisallowsCenteredExtraCharactersMultibyte() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->expectExceptionMessage('The number contains unrecognized characters: "foo8"'); // Since we test against other locales, we need the full implementation IntlTestHelper::requireFullIntl($this, false); @@ -583,7 +584,7 @@ public function testReverseTransformDisallowsCenteredExtraCharactersMultibyte() public function testReverseTransformIgnoresTrailingSpacesInExceptionMessage() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->expectExceptionMessage('The number contains unrecognized characters: "foo8"'); // Since we test against other locales, we need the full implementation IntlTestHelper::requireFullIntl($this, false); @@ -597,7 +598,7 @@ public function testReverseTransformIgnoresTrailingSpacesInExceptionMessage() public function testReverseTransformDisallowsTrailingExtraCharacters() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->expectExceptionMessage('The number contains unrecognized characters: "foo"'); $transformer = new NumberToLocalizedStringTransformer(); @@ -606,7 +607,7 @@ public function testReverseTransformDisallowsTrailingExtraCharacters() public function testReverseTransformDisallowsTrailingExtraCharactersMultibyte() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->expectExceptionMessage('The number contains unrecognized characters: "foo"'); // Since we test against other locales, we need the full implementation IntlTestHelper::requireFullIntl($this, false); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php index af487827a171..c4817538d073 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\PercentToLocalizedStringTransformer; use Symfony\Component\Intl\Util\IntlTestHelper; @@ -112,7 +113,7 @@ public function testTransformExpectsNumeric() { $transformer = new PercentToLocalizedStringTransformer(); - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer->transform('foo'); } @@ -121,7 +122,7 @@ public function testReverseTransformExpectsString() { $transformer = new PercentToLocalizedStringTransformer(); - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer->reverseTransform(1); } @@ -144,7 +145,7 @@ public function testDecimalSeparatorMayBeDotIfGroupingSeparatorIsNotDot() public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDot() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); // Since we test against "de_DE", we need the full implementation IntlTestHelper::requireFullIntl($this, '4.8.1.1'); @@ -157,7 +158,7 @@ public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDot() public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDotWithNoGroupSep() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); // Since we test against "de_DE", we need the full implementation IntlTestHelper::requireFullIntl($this, '4.8.1.1'); @@ -199,7 +200,7 @@ public function testDecimalSeparatorMayBeCommaIfGroupingSeparatorIsNotComma() public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsComma() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); IntlTestHelper::requireFullIntl($this, '4.8.1.1'); $transformer = new PercentToLocalizedStringTransformer(1, 'integer'); @@ -209,7 +210,7 @@ public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsComma() public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsCommaWithNoGroupSep() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); IntlTestHelper::requireFullIntl($this, '4.8.1.1'); $transformer = new PercentToLocalizedStringTransformer(1, 'integer'); @@ -237,7 +238,7 @@ public function testDecimalSeparatorMayBeCommaIfGroupingSeparatorIsCommaButNoGro public function testReverseTransformDisallowsLeadingExtraCharacters() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new PercentToLocalizedStringTransformer(); $transformer->reverseTransform('foo123'); @@ -245,7 +246,7 @@ public function testReverseTransformDisallowsLeadingExtraCharacters() public function testReverseTransformDisallowsCenteredExtraCharacters() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->expectExceptionMessage('The number contains unrecognized characters: "foo3"'); $transformer = new PercentToLocalizedStringTransformer(); @@ -257,7 +258,7 @@ public function testReverseTransformDisallowsCenteredExtraCharacters() */ public function testReverseTransformDisallowsCenteredExtraCharactersMultibyte() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->expectExceptionMessage('The number contains unrecognized characters: "foo8"'); // Since we test against other locales, we need the full implementation IntlTestHelper::requireFullIntl($this, false); @@ -271,7 +272,7 @@ public function testReverseTransformDisallowsCenteredExtraCharactersMultibyte() public function testReverseTransformDisallowsTrailingExtraCharacters() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->expectExceptionMessage('The number contains unrecognized characters: "foo"'); $transformer = new PercentToLocalizedStringTransformer(); @@ -283,7 +284,7 @@ public function testReverseTransformDisallowsTrailingExtraCharacters() */ public function testReverseTransformDisallowsTrailingExtraCharactersMultibyte() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->expectExceptionMessage('The number contains unrecognized characters: "foo"'); // Since we test against other locales, we need the full implementation IntlTestHelper::requireFullIntl($this, false); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/StringToFloatTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/StringToFloatTransformerTest.php index ee4e4f8a65e4..e48580baa54c 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/StringToFloatTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/StringToFloatTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\StringToFloatTransformer; class StringToFloatTransformerTest extends TestCase @@ -39,14 +40,14 @@ public function testTransform($from, $to) public function testFailIfTransformingANonString() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new StringToFloatTransformer(); $transformer->transform(1.0); } public function testFailIfTransformingANonNumericString() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new StringToFloatTransformer(); $transformer->transform('foobar'); } @@ -79,7 +80,7 @@ public function testReverseTransform($from, $to, int $scale = null) public function testFailIfReverseTransformingANonNumeric() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $transformer = new StringToFloatTransformer(); $transformer->reverseTransform('foobar'); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.php index b723a857e526..fdfd98357641 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\ValueToDuplicatesTransformer; class ValueToDuplicatesTransformerTest extends TestCase @@ -107,7 +108,7 @@ public function testReverseTransformZeroString() public function testReverseTransformPartiallyNull() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $input = [ 'a' => 'Foo', 'b' => 'Foo', @@ -119,7 +120,7 @@ public function testReverseTransformPartiallyNull() public function testReverseTransformDifferences() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $input = [ 'a' => 'Foo', 'b' => 'Bar', @@ -131,7 +132,7 @@ public function testReverseTransformDifferences() public function testReverseTransformRequiresArray() { - $this->expectException(\Symfony\Component\Form\Exception\TransformationFailedException::class); + $this->expectException(TransformationFailedException::class); $this->transformer->reverseTransform('12345'); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php index 98a93d196aaf..0be62fa1532f 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\EventListener; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Extension\Core\EventListener\MergeCollectionListener; use Symfony\Component\Form\FormEvent; @@ -185,7 +186,7 @@ public function testDoNothingIfNotAllowDelete($allowAdd) */ public function testRequireArrayOrTraversable($allowAdd, $allowDelete) { - $this->expectException(\Symfony\Component\Form\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $newData = 'no array or traversable'; $event = new FormEvent($this->form, $newData); $listener = new MergeCollectionListener($allowAdd, $allowDelete); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php index b33038bcd854..5e0fc84f02d7 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php @@ -14,6 +14,7 @@ use Doctrine\Common\Collections\ArrayCollection; use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper; use Symfony\Component\Form\Extension\Core\EventListener\ResizeFormListener; use Symfony\Component\Form\Extension\Core\Type\TextType; @@ -68,7 +69,7 @@ public function testPreSetDataResizesForm() public function testPreSetDataRequiresArrayOrTraversable() { - $this->expectException(\Symfony\Component\Form\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $data = 'no array or traversable'; $event = new FormEvent($this->form, $data); $listener = new ResizeFormListener('text', [], false, false); @@ -201,7 +202,7 @@ public function testOnSubmitNormDataDoesNothingIfNotAllowDelete() public function testOnSubmitNormDataRequiresArrayOrTraversable() { - $this->expectException(\Symfony\Component\Form\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $data = 'no array or traversable'; $event = new FormEvent($this->form, $data); $listener = new ResizeFormListener('text', [], false, false); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/BirthdayTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/BirthdayTypeTest.php index d682a6b1c25c..47028ac014a7 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/BirthdayTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/BirthdayTypeTest.php @@ -11,6 +11,8 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + /** * @author Stepan Anchugov */ @@ -20,7 +22,7 @@ class BirthdayTypeTest extends DateTypeTest public function testSetInvalidYearsOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'years' => 'bad value', ]); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/ButtonTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/ButtonTypeTest.php index 64793338757e..654e04649e9f 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/ButtonTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/ButtonTypeTest.php @@ -11,6 +11,9 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\Form\Button; +use Symfony\Component\Form\Exception\BadMethodCallException; + /** * @author Bernhard Schussek */ @@ -20,7 +23,7 @@ class ButtonTypeTest extends BaseTypeTest public function testCreateButtonInstances() { - $this->assertInstanceOf(\Symfony\Component\Form\Button::class, $this->factory->create(static::TESTED_TYPE)); + $this->assertInstanceOf(Button::class, $this->factory->create(static::TESTED_TYPE)); } /** @@ -29,7 +32,7 @@ public function testCreateButtonInstances() */ public function testSubmitNullUsesDefaultEmptyData($emptyData = 'empty', $expectedData = null) { - $this->expectException(\Symfony\Component\Form\Exception\BadMethodCallException::class); + $this->expectException(BadMethodCallException::class); $this->expectExceptionMessage('Buttons do not support empty data.'); parent::testSubmitNullUsesDefaultEmptyData($emptyData, $expectedData); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/CheckboxTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/CheckboxTypeTest.php index c8c03db043cc..93ca921b7c65 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/CheckboxTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/CheckboxTypeTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\CallbackTransformer; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; class CheckboxTypeTest extends BaseTypeTest { @@ -196,7 +197,7 @@ public function provideCustomFalseValues() public function testDontAllowNonArrayFalseValues() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->expectExceptionMessageMatches('/"false_values" with value "invalid" is expected to be of type "array"/'); $this->factory->create(static::TESTED_TYPE, null, [ 'false_values' => 'invalid', diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.php index c07722c9e307..7e5989d420a3 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.php @@ -13,6 +13,8 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView; use Symfony\Component\Form\ChoiceList\View\ChoiceView; +use Symfony\Component\Form\FormInterface; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; class ChoiceTypeTest extends BaseTypeTest { @@ -82,7 +84,7 @@ protected function tearDown(): void public function testChoicesOptionExpectsArrayOrTraversable() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'choices' => new \stdClass(), ]); @@ -90,7 +92,7 @@ public function testChoicesOptionExpectsArrayOrTraversable() public function testChoiceLoaderOptionExpectsChoiceLoaderInterface() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'choice_loader' => new \stdClass(), ]); @@ -98,7 +100,7 @@ public function testChoiceLoaderOptionExpectsChoiceLoaderInterface() public function testChoiceListAndChoicesCanBeEmpty() { - $this->assertInstanceOf(\Symfony\Component\Form\FormInterface::class, $this->factory->create(static::TESTED_TYPE, null, [])); + $this->assertInstanceOf(FormInterface::class, $this->factory->create(static::TESTED_TYPE, null, [])); } public function testExpandedChoicesOptionsTurnIntoChildren() @@ -1802,7 +1804,8 @@ public function testAdjustFullNameForMultipleNonExpanded() // https://github.com/symfony/symfony/issues/3298 public function testInitializeWithEmptyChoices() { - $this->assertInstanceOf(\Symfony\Component\Form\FormInterface::class, $this->factory->createNamed('name', static::TESTED_TYPE, null, [ + $this->assertInstanceOf( + FormInterface::class, $this->factory->createNamed('name', static::TESTED_TYPE, null, [ 'choices' => [], ])); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/CollectionTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/CollectionTypeTest.php index 1a56dd0474d9..e98a0c17443f 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/CollectionTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/CollectionTypeTest.php @@ -11,6 +11,8 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\Form\Exception\UnexpectedTypeException; +use Symfony\Component\Form\Form; use Symfony\Component\Form\Tests\Fixtures\Author; use Symfony\Component\Form\Tests\Fixtures\AuthorType; @@ -37,8 +39,8 @@ public function testSetDataAdjustsSize() ]); $form->setData(['foo@foo.com', 'foo@bar.com']); - $this->assertInstanceOf(\Symfony\Component\Form\Form::class, $form[0]); - $this->assertInstanceOf(\Symfony\Component\Form\Form::class, $form[1]); + $this->assertInstanceOf(Form::class, $form[0]); + $this->assertInstanceOf(Form::class, $form[1]); $this->assertCount(2, $form); $this->assertEquals('foo@foo.com', $form[0]->getData()); $this->assertEquals('foo@bar.com', $form[1]->getData()); @@ -48,7 +50,7 @@ public function testSetDataAdjustsSize() $this->assertEquals(20, $formAttrs1['maxlength']); $form->setData(['foo@baz.com']); - $this->assertInstanceOf(\Symfony\Component\Form\Form::class, $form[0]); + $this->assertInstanceOf(Form::class, $form[0]); $this->assertArrayNotHasKey(1, $form); $this->assertCount(1, $form); $this->assertEquals('foo@baz.com', $form[0]->getData()); @@ -61,7 +63,7 @@ public function testThrowsExceptionIfObjectIsNotTraversable() $form = $this->factory->create(static::TESTED_TYPE, null, [ 'entry_type' => TextTypeTest::TESTED_TYPE, ]); - $this->expectException(\Symfony\Component\Form\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $form->setData(new \stdClass()); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/DateTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/DateTypeTest.php index 58a42fd603a9..5891cc08aa29 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/DateTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/DateTypeTest.php @@ -15,6 +15,7 @@ use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormInterface; use Symfony\Component\Intl\Util\IntlTestHelper; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; class DateTypeTest extends BaseTypeTest { @@ -38,7 +39,7 @@ protected function tearDown(): void public function testInvalidWidgetOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'widget' => 'fake_widget', ]); @@ -46,7 +47,7 @@ public function testInvalidWidgetOption() public function testInvalidInputOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'input' => 'fake_input', ]); @@ -373,7 +374,7 @@ public function provideDateFormats() */ public function testThrowExceptionIfFormatIsNoPattern() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'format' => '0', 'html5' => false, @@ -384,7 +385,7 @@ public function testThrowExceptionIfFormatIsNoPattern() public function testThrowExceptionIfFormatDoesNotContainYearMonthAndDay() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->expectExceptionMessage('The "format" option should contain the letters "y", "M" and "d". Its current value is "yy".'); $this->factory->create(static::TESTED_TYPE, null, [ 'months' => [6, 7], @@ -394,7 +395,7 @@ public function testThrowExceptionIfFormatDoesNotContainYearMonthAndDay() public function testThrowExceptionIfFormatMissesYearMonthAndDayWithSingleTextWidget() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->expectExceptionMessage('The "format" option should contain the letters "y", "M" or "d". Its current value is "wrong".'); $this->factory->create(static::TESTED_TYPE, null, [ 'widget' => 'single_text', @@ -405,7 +406,7 @@ public function testThrowExceptionIfFormatMissesYearMonthAndDayWithSingleTextWid public function testThrowExceptionIfFormatIsNoConstant() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'format' => 105, ]); @@ -413,7 +414,7 @@ public function testThrowExceptionIfFormatIsNoConstant() public function testThrowExceptionIfFormatIsInvalid() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'format' => [], ]); @@ -421,7 +422,7 @@ public function testThrowExceptionIfFormatIsInvalid() public function testThrowExceptionIfYearsIsInvalid() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'years' => 'bad value', ]); @@ -429,7 +430,7 @@ public function testThrowExceptionIfYearsIsInvalid() public function testThrowExceptionIfMonthsIsInvalid() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'months' => 'bad value', ]); @@ -437,7 +438,7 @@ public function testThrowExceptionIfMonthsIsInvalid() public function testThrowExceptionIfDaysIsInvalid() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'days' => 'bad value', ]); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/FileTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/FileTypeTest.php index 7d3957e9420d..5db5e9e8ab92 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/FileTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/FileTypeTest.php @@ -25,7 +25,7 @@ class FileTypeTest extends BaseTypeTest protected function getExtensions() { - $translator = $this->getMockBuilder(TranslatorInterface::class)->getMock(); + $translator = $this->createMock(TranslatorInterface::class); $translator->expects($this->any())->method('trans')->willReturnArgument(0); return array_merge(parent::getExtensions(), [new CoreExtension(null, null, $translator)]); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php index 0e737721e939..dff01e081bd0 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php @@ -13,15 +13,19 @@ use Symfony\Component\Form\CallbackTransformer; use Symfony\Component\Form\DataMapperInterface; +use Symfony\Component\Form\Exception\InvalidArgumentException; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\Type\CurrencyType; use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Validator\ValidatorExtension; +use Symfony\Component\Form\Form; +use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormError; use Symfony\Component\Form\Forms; use Symfony\Component\Form\Tests\Fixtures\Author; use Symfony\Component\Form\Tests\Fixtures\FixedDataTransformer; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\PropertyAccess\PropertyPath; use Symfony\Component\Validator\Validation; @@ -63,7 +67,7 @@ class FormTypeTest extends BaseTypeTest public function testCreateFormInstances() { - $this->assertInstanceOf(\Symfony\Component\Form\Form::class, $this->factory->create(static::TESTED_TYPE)); + $this->assertInstanceOf(Form::class, $this->factory->create(static::TESTED_TYPE)); } public function testPassRequiredAsOption() @@ -149,28 +153,31 @@ public function testPassMaxLengthToView() public function testDataClassMayBeNull() { - $this->assertInstanceOf(\Symfony\Component\Form\FormBuilderInterface::class, $this->factory->createBuilder(static::TESTED_TYPE, null, [ + $this->assertInstanceOf( + FormBuilderInterface::class, $this->factory->createBuilder(static::TESTED_TYPE, null, [ 'data_class' => null, ])); } public function testDataClassMayBeAbstractClass() { - $this->assertInstanceOf(\Symfony\Component\Form\FormBuilderInterface::class, $this->factory->createBuilder(static::TESTED_TYPE, null, [ + $this->assertInstanceOf( + FormBuilderInterface::class, $this->factory->createBuilder(static::TESTED_TYPE, null, [ 'data_class' => 'Symfony\Component\Form\Tests\Fixtures\AbstractAuthor', ])); } public function testDataClassMayBeInterface() { - $this->assertInstanceOf(\Symfony\Component\Form\FormBuilderInterface::class, $this->factory->createBuilder(static::TESTED_TYPE, null, [ + $this->assertInstanceOf( + FormBuilderInterface::class, $this->factory->createBuilder(static::TESTED_TYPE, null, [ 'data_class' => 'Symfony\Component\Form\Tests\Fixtures\AuthorInterface', ])); } public function testDataClassMustBeValidClassOrInterface() { - $this->expectException(\Symfony\Component\Form\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->factory->createBuilder(static::TESTED_TYPE, null, [ 'data_class' => 'foobar', ]); @@ -337,7 +344,7 @@ public function testSubmitWithEmptyDataUsesEmptyDataOption() public function testAttributesException() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, ['attr' => '']); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/NumberTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/NumberTypeTest.php index 7ea85586fa90..38718fb42a08 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/NumberTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/NumberTypeTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Intl\Util\IntlTestHelper; class NumberTypeTest extends BaseTypeTest @@ -200,7 +201,7 @@ public function testIgnoresDefaultLocaleToRenderHtml5NumberWidgets() public function testGroupingNotAllowedWithHtml5Widget() { - $this->expectException(\Symfony\Component\Form\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'grouping' => true, 'html5' => true, diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/RepeatedTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/RepeatedTypeTest.php index d4233aa58d85..60d565787699 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/RepeatedTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/RepeatedTypeTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Form\Form; use Symfony\Component\Form\Tests\Fixtures\NotMappedType; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; class RepeatedTypeTest extends BaseTypeTest { @@ -116,7 +117,7 @@ public function notMappedConfigurationKeys() public function testSetInvalidOptions() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'type' => TextTypeTest::TESTED_TYPE, 'options' => 'bad value', @@ -125,7 +126,7 @@ public function testSetInvalidOptions() public function testSetInvalidFirstOptions() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'type' => TextTypeTest::TESTED_TYPE, 'first_options' => 'bad value', @@ -134,7 +135,7 @@ public function testSetInvalidFirstOptions() public function testSetInvalidSecondOptions() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'type' => TextTypeTest::TESTED_TYPE, 'second_options' => 'bad value', diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/SubmitTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/SubmitTypeTest.php index fdabed0d0dd0..8a16175d769b 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/SubmitTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/SubmitTypeTest.php @@ -11,6 +11,8 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\Form\SubmitButton; + /** * @author Bernhard Schussek */ @@ -20,7 +22,7 @@ class SubmitTypeTest extends ButtonTypeTest public function testCreateSubmitButtonInstances() { - $this->assertInstanceOf(\Symfony\Component\Form\SubmitButton::class, $this->factory->create(static::TESTED_TYPE)); + $this->assertInstanceOf(SubmitButton::class, $this->factory->create(static::TESTED_TYPE)); } public function testNotClickedByDefault() diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimeTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimeTypeTest.php index 460773867087..4c9700b7ef89 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimeTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimeTypeTest.php @@ -12,8 +12,10 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\ChoiceList\View\ChoiceView; +use Symfony\Component\Form\Exception\InvalidConfigurationException; use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormInterface; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; class TimeTypeTest extends BaseTypeTest { @@ -858,7 +860,7 @@ public function testSecondErrorsBubbleUp($widget) public function testInitializeWithSecondsAndWithoutMinutes() { - $this->expectException(\Symfony\Component\Form\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'with_minutes' => false, 'with_seconds' => true, @@ -867,7 +869,7 @@ public function testInitializeWithSecondsAndWithoutMinutes() public function testThrowExceptionIfHoursIsInvalid() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'hours' => 'bad value', ]); @@ -875,7 +877,7 @@ public function testThrowExceptionIfHoursIsInvalid() public function testThrowExceptionIfMinutesIsInvalid() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'minutes' => 'bad value', ]); @@ -883,7 +885,7 @@ public function testThrowExceptionIfMinutesIsInvalid() public function testThrowExceptionIfSecondsIsInvalid() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'seconds' => 'bad value', ]); @@ -891,7 +893,7 @@ public function testThrowExceptionIfSecondsIsInvalid() public function testReferenceDateTimezoneMustMatchModelTimezone() { - $this->expectException(\Symfony\Component\Form\Exception\InvalidConfigurationException::class); + $this->expectException(InvalidConfigurationException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'model_timezone' => 'UTC', 'view_timezone' => 'Europe/Berlin', diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimezoneTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimezoneTypeTest.php index 50e7a045c256..35b7355ebed0 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimezoneTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimezoneTypeTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\ChoiceList\View\ChoiceView; +use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Intl\Util\IntlTestHelper; class TimezoneTypeTest extends BaseTypeTest @@ -90,7 +91,7 @@ public function testFilterByRegions() */ public function testFilterByRegionsWithIntl() { - $this->expectException(\Symfony\Component\Form\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('The "regions" option can only be used if the "intl" option is set to false.'); $this->factory->create(static::TESTED_TYPE, null, ['regions' => \DateTimeZone::EUROPE, 'intl' => true]); } @@ -192,7 +193,7 @@ public function testChoiceTranslationLocaleOptionWithIntl() public function testChoiceTranslationLocaleOptionWithoutIntl() { - $this->expectException(\Symfony\Component\Form\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('The "choice_translation_locale" option can only be used if the "intl" option is set to true.'); $this->factory->create(static::TESTED_TYPE, null, [ 'choice_translation_locale' => 'uk', diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/UrlTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/UrlTypeTest.php index efcda8426136..b9387d01a45e 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/UrlTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/UrlTypeTest.php @@ -11,6 +11,8 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + class UrlTypeTest extends TextTypeTest { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\UrlType'; @@ -75,7 +77,7 @@ public function testSubmitAddsNoDefaultProtocolIfSetToNull() public function testThrowExceptionIfDefaultProtocolIsInvalid() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'default_protocol' => [], ]); diff --git a/src/Symfony/Component/Form/Tests/Extension/Csrf/EventListener/CsrfValidationListenerTest.php b/src/Symfony/Component/Form/Tests/Extension/Csrf/EventListener/CsrfValidationListenerTest.php index 0debb9e77779..fc0ae8e45de8 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Csrf/EventListener/CsrfValidationListenerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Csrf/EventListener/CsrfValidationListenerTest.php @@ -76,12 +76,7 @@ public function testArrayCsrfToken() public function testMaxPostSizeExceeded() { - $serverParams = $this - ->getMockBuilder(ServerParams::class) - ->disableOriginalConstructor() - ->getMock() - ; - + $serverParams = $this->createMock(ServerParams::class); $serverParams ->expects($this->once()) ->method('hasPostMaxSizeBeenExceeded') diff --git a/src/Symfony/Component/Form/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php b/src/Symfony/Component/Form/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php index abde92b1559f..b9fa3c5ca89a 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php @@ -45,8 +45,8 @@ class FormTypeCsrfExtensionTest extends TypeTestCase protected function setUp(): void { - $this->tokenManager = $this->getMockBuilder(CsrfTokenManagerInterface::class)->getMock(); - $this->translator = $this->getMockBuilder(TranslatorInterface::class)->getMock(); + $this->tokenManager = $this->createMock(CsrfTokenManagerInterface::class); + $this->translator = $this->createMock(TranslatorInterface::class); $this->translator->expects($this->any())->method('trans')->willReturnArgument(0); parent::setUp(); diff --git a/src/Symfony/Component/Form/Tests/Extension/DataCollector/DataCollectorExtensionTest.php b/src/Symfony/Component/Form/Tests/Extension/DataCollector/DataCollectorExtensionTest.php index c5a5fe10032b..6f1b1b1272f8 100644 --- a/src/Symfony/Component/Form/Tests/Extension/DataCollector/DataCollectorExtensionTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/DataCollector/DataCollectorExtensionTest.php @@ -14,6 +14,8 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\Form\Extension\DataCollector\DataCollectorExtension; +use Symfony\Component\Form\Extension\DataCollector\FormDataCollectorInterface; +use Symfony\Component\Form\Extension\DataCollector\Type\DataCollectorTypeExtension; class DataCollectorExtensionTest extends TestCase { @@ -29,7 +31,7 @@ class DataCollectorExtensionTest extends TestCase protected function setUp(): void { - $this->dataCollector = $this->getMockBuilder(\Symfony\Component\Form\Extension\DataCollector\FormDataCollectorInterface::class)->getMock(); + $this->dataCollector = $this->createMock(FormDataCollectorInterface::class); $this->extension = new DataCollectorExtension($this->dataCollector); } @@ -39,6 +41,6 @@ public function testLoadTypeExtensions() $this->assertIsArray($typeExtensions); $this->assertCount(1, $typeExtensions); - $this->assertInstanceOf(\Symfony\Component\Form\Extension\DataCollector\Type\DataCollectorTypeExtension::class, array_shift($typeExtensions)); + $this->assertInstanceOf(DataCollectorTypeExtension::class, array_shift($typeExtensions)); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/DataCollector/FormDataCollectorTest.php b/src/Symfony/Component/Form/Tests/Extension/DataCollector/FormDataCollectorTest.php index 7d8c952ae0f2..836d9d8ba682 100644 --- a/src/Symfony/Component/Form/Tests/Extension/DataCollector/FormDataCollectorTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/DataCollector/FormDataCollectorTest.php @@ -20,6 +20,7 @@ use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\DataCollector\FormDataCollector; +use Symfony\Component\Form\Extension\DataCollector\FormDataExtractorInterface; use Symfony\Component\Form\Form; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormFactory; @@ -77,7 +78,7 @@ class FormDataCollectorTest extends TestCase protected function setUp(): void { - $this->dataExtractor = $this->getMockBuilder(\Symfony\Component\Form\Extension\DataCollector\FormDataExtractorInterface::class)->getMock(); + $this->dataExtractor = $this->createMock(FormDataExtractorInterface::class); $this->dataCollector = new FormDataCollector($this->dataExtractor); $this->dispatcher = new EventDispatcher(); $this->factory = new FormFactory(new FormRegistry([new CoreExtension()], new ResolvedFormTypeFactory())); diff --git a/src/Symfony/Component/Form/Tests/Extension/DataCollector/FormDataExtractorTest.php b/src/Symfony/Component/Form/Tests/Extension/DataCollector/FormDataExtractorTest.php index cda0bd24da91..e56861dead0b 100644 --- a/src/Symfony/Component/Form/Tests/Extension/DataCollector/FormDataExtractorTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/DataCollector/FormDataExtractorTest.php @@ -13,13 +13,17 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Form\CallbackTransformer; +use Symfony\Component\Form\DataMapperInterface; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\Type\HiddenType; use Symfony\Component\Form\Extension\DataCollector\FormDataExtractor; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormError; +use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\FormView; +use Symfony\Component\Form\ResolvedFormTypeInterface; use Symfony\Component\Form\Tests\Fixtures\FixedDataTransformer; use Symfony\Component\Validator\ConstraintViolation; use Symfony\Component\VarDumper\Test\VarDumperTestTrait; @@ -49,13 +53,13 @@ class FormDataExtractorTest extends TestCase protected function setUp(): void { $this->dataExtractor = new FormDataExtractor(); - $this->dispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class)->getMock(); - $this->factory = $this->getMockBuilder(\Symfony\Component\Form\FormFactoryInterface::class)->getMock(); + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); + $this->factory = $this->createMock(FormFactoryInterface::class); } public function testExtractConfiguration() { - $type = $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormTypeInterface::class)->getMock(); + $type = $this->createMock(ResolvedFormTypeInterface::class); $type->expects($this->any()) ->method('getInnerType') ->willReturn(new HiddenType()); @@ -76,7 +80,7 @@ public function testExtractConfiguration() public function testExtractConfigurationSortsPassedOptions() { - $type = $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormTypeInterface::class)->getMock(); + $type = $this->createMock(ResolvedFormTypeInterface::class); $type->expects($this->any()) ->method('getInnerType') ->willReturn(new HiddenType()); @@ -110,7 +114,7 @@ public function testExtractConfigurationSortsPassedOptions() public function testExtractConfigurationSortsResolvedOptions() { - $type = $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormTypeInterface::class)->getMock(); + $type = $this->createMock(ResolvedFormTypeInterface::class); $type->expects($this->any()) ->method('getInnerType') ->willReturn(new HiddenType()); @@ -141,18 +145,18 @@ public function testExtractConfigurationSortsResolvedOptions() public function testExtractConfigurationBuildsIdRecursively() { - $type = $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormTypeInterface::class)->getMock(); + $type = $this->createMock(ResolvedFormTypeInterface::class); $type->expects($this->any()) ->method('getInnerType') ->willReturn(new HiddenType()); $grandParent = $this->createBuilder('grandParent') ->setCompound(true) - ->setDataMapper($this->getMockBuilder(\Symfony\Component\Form\DataMapperInterface::class)->getMock()) + ->setDataMapper($this->createMock(DataMapperInterface::class)) ->getForm(); $parent = $this->createBuilder('parent') ->setCompound(true) - ->setDataMapper($this->getMockBuilder(\Symfony\Component\Form\DataMapperInterface::class)->getMock()) + ->setDataMapper($this->createMock(DataMapperInterface::class)) ->getForm(); $form = $this->createBuilder('name') ->setType($type) diff --git a/src/Symfony/Component/Form/Tests/Extension/DataCollector/Type/DataCollectorTypeExtensionTest.php b/src/Symfony/Component/Form/Tests/Extension/DataCollector/Type/DataCollectorTypeExtensionTest.php index 69c40605c932..3f5997328f23 100644 --- a/src/Symfony/Component/Form/Tests/Extension/DataCollector/Type/DataCollectorTypeExtensionTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/DataCollector/Type/DataCollectorTypeExtensionTest.php @@ -13,7 +13,10 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Extension\DataCollector\EventListener\DataCollectorListener; +use Symfony\Component\Form\Extension\DataCollector\FormDataCollectorInterface; use Symfony\Component\Form\Extension\DataCollector\Type\DataCollectorTypeExtension; +use Symfony\Component\Form\Test\FormBuilderInterface; class DataCollectorTypeExtensionTest extends TestCase { @@ -29,7 +32,7 @@ class DataCollectorTypeExtensionTest extends TestCase protected function setUp(): void { - $this->dataCollector = $this->getMockBuilder(\Symfony\Component\Form\Extension\DataCollector\FormDataCollectorInterface::class)->getMock(); + $this->dataCollector = $this->createMock(FormDataCollectorInterface::class); $this->extension = new DataCollectorTypeExtension($this->dataCollector); } @@ -43,10 +46,10 @@ public function testGetExtendedType() public function testBuildForm() { - $builder = $this->getMockBuilder(\Symfony\Component\Form\Test\FormBuilderInterface::class)->getMock(); + $builder = $this->createMock(FormBuilderInterface::class); $builder->expects($this->atLeastOnce()) ->method('addEventSubscriber') - ->with($this->isInstanceOf(\Symfony\Component\Form\Extension\DataCollector\EventListener\DataCollectorListener::class)); + ->with($this->isInstanceOf(DataCollectorListener::class)); $this->extension->buildForm($builder, []); } diff --git a/src/Symfony/Component/Form/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php b/src/Symfony/Component/Form/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php index 157ebe3390ab..eb0a13c3334a 100644 --- a/src/Symfony/Component/Form/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Form\AbstractTypeExtension; +use Symfony\Component\Form\Exception\InvalidArgumentException; use Symfony\Component\Form\Extension\DependencyInjection\DependencyInjectionExtension; use Symfony\Component\Form\FormTypeGuesserChain; use Symfony\Component\Form\FormTypeGuesserInterface; @@ -43,7 +44,7 @@ public function testGetTypeExtensions() public function testThrowExceptionForInvalidExtendedType() { - $this->expectException(\Symfony\Component\Form\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage(sprintf('The extended type "unmatched" specified for the type extension class "%s" does not match any of the actual extended types (["test"]).', TestTypeExtension::class)); $extensions = [ @@ -57,7 +58,7 @@ public function testThrowExceptionForInvalidExtendedType() public function testGetTypeGuesser() { - $extension = new DependencyInjectionExtension(new ContainerBuilder(), [], [$this->getMockBuilder(FormTypeGuesserInterface::class)->getMock()]); + $extension = new DependencyInjectionExtension(new ContainerBuilder(), [], [$this->createMock(FormTypeGuesserInterface::class)]); $this->assertInstanceOf(FormTypeGuesserChain::class, $extension->getTypeGuesser()); } diff --git a/src/Symfony/Component/Form/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.php b/src/Symfony/Component/Form/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.php index d2bdedaeeba0..69be3777cca3 100644 --- a/src/Symfony/Component/Form/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Tests\Extension\HttpFoundation; +use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler; use Symfony\Component\Form\Tests\AbstractRequestHandlerTest; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -23,13 +24,13 @@ class HttpFoundationRequestHandlerTest extends AbstractRequestHandlerTest { public function testRequestShouldNotBeNull() { - $this->expectException(\Symfony\Component\Form\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $this->requestHandler->handleRequest($this->createForm('name', 'GET')); } public function testRequestShouldBeInstanceOfRequest() { - $this->expectException(\Symfony\Component\Form\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $this->requestHandler->handleRequest($this->createForm('name', 'GET'), new \stdClass()); } diff --git a/src/Symfony/Component/Form/Tests/FormBuilderTest.php b/src/Symfony/Component/Form/Tests/FormBuilderTest.php index 6db3cc1628ae..878d52725903 100644 --- a/src/Symfony/Component/Form/Tests/FormBuilderTest.php +++ b/src/Symfony/Component/Form/Tests/FormBuilderTest.php @@ -12,10 +12,15 @@ namespace Symfony\Component\Form\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Form\ButtonBuilder; +use Symfony\Component\Form\Exception\InvalidArgumentException; +use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Extension\Core\Type\SubmitType; +use Symfony\Component\Form\Form; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormFactoryBuilder; +use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\SubmitButtonBuilder; class FormBuilderTest extends TestCase @@ -26,8 +31,8 @@ class FormBuilderTest extends TestCase protected function setUp(): void { - $this->dispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class)->getMock(); - $this->factory = $this->getMockBuilder(\Symfony\Component\Form\FormFactoryInterface::class)->getMock(); + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); + $this->factory = $this->createMock(FormFactoryInterface::class); $this->builder = new FormBuilder('name', null, $this->dispatcher, $this->factory); } @@ -51,13 +56,13 @@ public function testNoSetName() public function testAddNameNoStringAndNoInteger() { - $this->expectException(\Symfony\Component\Form\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $this->builder->add(true); } public function testAddTypeNoString() { - $this->expectException(\Symfony\Component\Form\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $this->builder->add('foo', 1234); } @@ -139,7 +144,7 @@ public function testRemoveAndGetForm() $this->builder->add('foo', 'Symfony\Component\Form\Extension\Core\Type\TextType'); $this->builder->remove('foo'); $form = $this->builder->getForm(); - $this->assertInstanceOf(\Symfony\Component\Form\Form::class, $form); + $this->assertInstanceOf(Form::class, $form); } public function testCreateNoTypeNo() @@ -162,7 +167,7 @@ public function testAddButton() public function testGetUnknown() { - $this->expectException(\Symfony\Component\Form\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The child with the name "foo" does not exist.'); $this->builder->get('foo'); @@ -229,10 +234,7 @@ public function testGetButtonBuilderBeforeExplicitlyResolvingAllChildren() private function getFormBuilder($name = 'name') { - $mock = $this->getMockBuilder(FormBuilder::class) - ->disableOriginalConstructor() - ->getMock(); - + $mock = $this->createMock(FormBuilder::class); $mock->expects($this->any()) ->method('getName') ->willReturn($name); diff --git a/src/Symfony/Component/Form/Tests/FormConfigTest.php b/src/Symfony/Component/Form/Tests/FormConfigTest.php index cc943fcda24c..d1f1b9c3edad 100644 --- a/src/Symfony/Component/Form/Tests/FormConfigTest.php +++ b/src/Symfony/Component/Form/Tests/FormConfigTest.php @@ -12,7 +12,9 @@ namespace Symfony\Component\Form\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Form\FormConfigBuilder; +use Symfony\Component\Form\NativeRequestHandler; /** * @author Bernhard Schussek @@ -65,7 +67,7 @@ public function getHtml4Ids() */ public function testNameAcceptsOnlyNamesValidAsIdsInHtml4($name, $expectedException = null) { - $dispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class)->getMock(); + $dispatcher = $this->createMock(EventDispatcherInterface::class); if (null !== $expectedException) { $this->expectException($expectedException); @@ -80,7 +82,7 @@ public function testGetRequestHandlerCreatesNativeRequestHandlerIfNotSet() { $config = $this->getConfigBuilder()->getFormConfig(); - $this->assertInstanceOf(\Symfony\Component\Form\NativeRequestHandler::class, $config->getRequestHandler()); + $this->assertInstanceOf(NativeRequestHandler::class, $config->getRequestHandler()); } public function testGetRequestHandlerReusesNativeRequestHandlerInstance() @@ -133,7 +135,7 @@ public function testSetMethodAllowsPatch() private function getConfigBuilder($name = 'name') { - $dispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class)->getMock(); + $dispatcher = $this->createMock(EventDispatcherInterface::class); return new FormConfigBuilder($name, null, $dispatcher); } diff --git a/src/Symfony/Component/Form/Tests/FormErrorIteratorTest.php b/src/Symfony/Component/Form/Tests/FormErrorIteratorTest.php index 1d21b074f561..b818dcd8c487 100644 --- a/src/Symfony/Component/Form/Tests/FormErrorIteratorTest.php +++ b/src/Symfony/Component/Form/Tests/FormErrorIteratorTest.php @@ -16,6 +16,7 @@ use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormErrorIterator; +use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Validator\ConstraintViolation; class FormErrorIteratorTest extends TestCase @@ -33,7 +34,7 @@ public function testFindByCodes($code, $violationsCount) 'form', null, new EventDispatcher(), - $this->getMockBuilder(\Symfony\Component\Form\FormFactoryInterface::class)->getMock(), + $this->createMock(FormFactoryInterface::class), [] ); diff --git a/src/Symfony/Component/Form/Tests/FormFactoryBuilderTest.php b/src/Symfony/Component/Form/Tests/FormFactoryBuilderTest.php index 22f6c49f2fbb..9f4825e3fcdf 100644 --- a/src/Symfony/Component/Form/Tests/FormFactoryBuilderTest.php +++ b/src/Symfony/Component/Form/Tests/FormFactoryBuilderTest.php @@ -12,7 +12,9 @@ namespace Symfony\Component\Form\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\FormFactory; use Symfony\Component\Form\FormFactoryBuilder; +use Symfony\Component\Form\FormTypeGuesserInterface; use Symfony\Component\Form\Tests\Fixtures\FooType; class FormFactoryBuilderTest extends TestCase @@ -23,11 +25,11 @@ class FormFactoryBuilderTest extends TestCase protected function setUp(): void { - $factory = new \ReflectionClass(\Symfony\Component\Form\FormFactory::class); + $factory = new \ReflectionClass(FormFactory::class); $this->registry = $factory->getProperty('registry'); $this->registry->setAccessible(true); - $this->guesser = $this->getMockBuilder(\Symfony\Component\Form\FormTypeGuesserInterface::class)->getMock(); + $this->guesser = $this->createMock(FormTypeGuesserInterface::class); $this->type = new FooType(); } diff --git a/src/Symfony/Component/Form/Tests/FormFactoryTest.php b/src/Symfony/Component/Form/Tests/FormFactoryTest.php index e60bacaee69a..0ea4bb26bfd1 100644 --- a/src/Symfony/Component/Form/Tests/FormFactoryTest.php +++ b/src/Symfony/Component/Form/Tests/FormFactoryTest.php @@ -14,12 +14,18 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormFactory; +use Symfony\Component\Form\FormRegistryInterface; use Symfony\Component\Form\FormTypeGuesserChain; +use Symfony\Component\Form\FormTypeGuesserInterface; use Symfony\Component\Form\Guess\Guess; use Symfony\Component\Form\Guess\TypeGuess; use Symfony\Component\Form\Guess\ValueGuess; +use Symfony\Component\Form\ResolvedFormType; +use Symfony\Component\Form\ResolvedFormTypeInterface; +use Symfony\Component\Form\Test\FormBuilderInterface; /** * @author Bernhard Schussek @@ -53,10 +59,10 @@ class FormFactoryTest extends TestCase protected function setUp(): void { - $this->guesser1 = $this->getMockBuilder(\Symfony\Component\Form\FormTypeGuesserInterface::class)->getMock(); - $this->guesser2 = $this->getMockBuilder(\Symfony\Component\Form\FormTypeGuesserInterface::class)->getMock(); - $this->registry = $this->getMockBuilder(\Symfony\Component\Form\FormRegistryInterface::class)->getMock(); - $this->builder = $this->getMockBuilder(\Symfony\Component\Form\Test\FormBuilderInterface::class)->getMock(); + $this->guesser1 = $this->createMock(FormTypeGuesserInterface::class); + $this->guesser2 = $this->createMock(FormTypeGuesserInterface::class); + $this->registry = $this->createMock(FormRegistryInterface::class); + $this->builder = $this->createMock(FormBuilderInterface::class); $this->factory = new FormFactory($this->registry); $this->registry->expects($this->any()) @@ -151,14 +157,14 @@ public function testCreateNamedBuilderDoesNotOverrideExistingDataOption() public function testCreateNamedBuilderThrowsUnderstandableException() { - $this->expectException(\Symfony\Component\Form\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $this->expectExceptionMessage('Expected argument of type "string", "stdClass" given'); $this->factory->createNamedBuilder('name', new \stdClass()); } public function testCreateThrowsUnderstandableException() { - $this->expectException(\Symfony\Component\Form\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $this->expectExceptionMessage('Expected argument of type "string", "stdClass" given'); $this->factory->create(new \stdClass()); } @@ -169,10 +175,7 @@ public function testCreateUsesBlockPrefixIfTypeGivenAsString() $resolvedOptions = ['a' => '2', 'b' => '3']; // the interface does not have the method, so use the real class - $resolvedType = $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormType::class) - ->disableOriginalConstructor() - ->getMock(); - + $resolvedType = $this->createMock(ResolvedFormType::class); $resolvedType->expects($this->any()) ->method('getBlockPrefix') ->willReturn('TYPE_PREFIX'); @@ -239,7 +242,7 @@ public function testCreateNamed() public function testCreateBuilderForPropertyWithoutTypeGuesser() { - $registry = $this->getMockBuilder(\Symfony\Component\Form\FormRegistryInterface::class)->getMock(); + $registry = $this->createMock(FormRegistryInterface::class); $factory = $this->getMockBuilder(FormFactory::class) ->setMethods(['createNamedBuilder']) ->setConstructorArgs([$registry]) @@ -485,6 +488,6 @@ private function getMockFactory(array $methods = []) private function getMockResolvedType() { - return $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormTypeInterface::class)->getMock(); + return $this->createMock(ResolvedFormTypeInterface::class); } } diff --git a/src/Symfony/Component/Form/Tests/FormRegistryTest.php b/src/Symfony/Component/Form/Tests/FormRegistryTest.php index 3b1518f54982..bcffa4dc6117 100644 --- a/src/Symfony/Component/Form/Tests/FormRegistryTest.php +++ b/src/Symfony/Component/Form/Tests/FormRegistryTest.php @@ -13,9 +13,14 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\Exception\InvalidArgumentException; +use Symfony\Component\Form\Exception\LogicException; +use Symfony\Component\Form\FormExtensionInterface; use Symfony\Component\Form\FormRegistry; use Symfony\Component\Form\FormTypeGuesserChain; +use Symfony\Component\Form\FormTypeGuesserInterface; use Symfony\Component\Form\ResolvedFormType; +use Symfony\Component\Form\ResolvedFormTypeFactory; use Symfony\Component\Form\ResolvedFormTypeFactoryInterface; use Symfony\Component\Form\ResolvedFormTypeInterface; use Symfony\Component\Form\Tests\Fixtures\FooSubType; @@ -65,9 +70,9 @@ class FormRegistryTest extends TestCase protected function setUp(): void { - $this->resolvedTypeFactory = $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormTypeFactory::class)->getMock(); - $this->guesser1 = $this->getMockBuilder(\Symfony\Component\Form\FormTypeGuesserInterface::class)->getMock(); - $this->guesser2 = $this->getMockBuilder(\Symfony\Component\Form\FormTypeGuesserInterface::class)->getMock(); + $this->resolvedTypeFactory = $this->createMock(ResolvedFormTypeFactory::class); + $this->guesser1 = $this->createMock(FormTypeGuesserInterface::class); + $this->guesser2 = $this->createMock(FormTypeGuesserInterface::class); $this->extension1 = new TestExtension($this->guesser1); $this->extension2 = new TestExtension($this->guesser2); $this->registry = new FormRegistry([ @@ -106,13 +111,13 @@ public function testLoadUnregisteredType() public function testFailIfUnregisteredTypeNoClass() { - $this->expectException(\Symfony\Component\Form\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->registry->getType('Symfony\Blubb'); } public function testFailIfUnregisteredTypeNoFormType() { - $this->expectException(\Symfony\Component\Form\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->registry->getType('stdClass'); } @@ -158,7 +163,7 @@ public function testGetTypeConnectsParent() public function testFormCannotHaveItselfAsAParent() { - $this->expectException(\Symfony\Component\Form\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Circular reference detected for form type "Symfony\Component\Form\Tests\Fixtures\FormWithSameParentType" (Symfony\Component\Form\Tests\Fixtures\FormWithSameParentType > Symfony\Component\Form\Tests\Fixtures\FormWithSameParentType).'); $type = new FormWithSameParentType(); @@ -169,7 +174,7 @@ public function testFormCannotHaveItselfAsAParent() public function testRecursiveFormDependencies() { - $this->expectException(\Symfony\Component\Form\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Circular reference detected for form type "Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeFoo" (Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeFoo > Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeBar > Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeBaz > Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeFoo).'); $foo = new RecursiveFormTypeFoo(); $bar = new RecursiveFormTypeBar(); @@ -184,7 +189,7 @@ public function testRecursiveFormDependencies() public function testGetTypeThrowsExceptionIfTypeNotFound() { - $this->expectException(\Symfony\Component\Form\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->registry->getType('bar'); } @@ -230,7 +235,7 @@ public function testGetTypeGuesser() $this->assertEquals($expectedGuesser, $this->registry->getTypeGuesser()); $registry = new FormRegistry( - [$this->getMockBuilder(\Symfony\Component\Form\FormExtensionInterface::class)->getMock()], + [$this->createMock(FormExtensionInterface::class)], $this->resolvedTypeFactory ); diff --git a/src/Symfony/Component/Form/Tests/FormRendererTest.php b/src/Symfony/Component/Form/Tests/FormRendererTest.php index 66fbdd79ecf0..00184ae2c5d6 100644 --- a/src/Symfony/Component/Form/Tests/FormRendererTest.php +++ b/src/Symfony/Component/Form/Tests/FormRendererTest.php @@ -12,12 +12,13 @@ namespace Symfony\Component\Form\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\FormRenderer; class FormRendererTest extends TestCase { public function testHumanize() { - $renderer = $this->getMockBuilder(\Symfony\Component\Form\FormRenderer::class) + $renderer = $this->getMockBuilder(FormRenderer::class) ->setMethods(null) ->disableOriginalConstructor() ->getMock() diff --git a/src/Symfony/Component/Form/Tests/NativeRequestHandlerTest.php b/src/Symfony/Component/Form/Tests/NativeRequestHandlerTest.php index d9e055b86bb2..8bbf0793ff89 100644 --- a/src/Symfony/Component/Form/Tests/NativeRequestHandlerTest.php +++ b/src/Symfony/Component/Form/Tests/NativeRequestHandlerTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Tests; +use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\NativeRequestHandler; /** @@ -50,7 +51,7 @@ protected function tearDown(): void public function testRequestShouldBeNull() { - $this->expectException(\Symfony\Component\Form\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $this->requestHandler->handleRequest($this->createForm('name', 'GET'), 'request'); } diff --git a/src/Symfony/Component/Form/Tests/ResolvedFormTypeTest.php b/src/Symfony/Component/Form/Tests/ResolvedFormTypeTest.php index 5eb74334891a..178efd9258fc 100644 --- a/src/Symfony/Component/Form/Tests/ResolvedFormTypeTest.php +++ b/src/Symfony/Component/Form/Tests/ResolvedFormTypeTest.php @@ -13,12 +13,19 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\Form\AbstractTypeExtension; +use Symfony\Component\Form\DataMapperInterface; use Symfony\Component\Form\Extension\Core\Type\HiddenType; use Symfony\Component\Form\Form; use Symfony\Component\Form\FormConfigInterface; +use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\FormTypeExtensionInterface; use Symfony\Component\Form\FormTypeInterface; +use Symfony\Component\Form\FormView; use Symfony\Component\Form\ResolvedFormType; +use Symfony\Component\Form\Test\FormBuilderInterface; +use Symfony\Component\OptionsResolver\Exception\MissingOptionsException; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -73,9 +80,9 @@ class ResolvedFormTypeTest extends TestCase protected function setUp(): void { - $this->dispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class)->getMock(); - $this->factory = $this->getMockBuilder(\Symfony\Component\Form\FormFactoryInterface::class)->getMock(); - $this->dataMapper = $this->getMockBuilder(\Symfony\Component\Form\DataMapperInterface::class)->getMock(); + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); + $this->factory = $this->createMock(FormFactoryInterface::class); + $this->dataMapper = $this->createMock(DataMapperInterface::class); $this->parentType = $this->getMockFormType(); $this->type = $this->getMockFormType(); $this->extension1 = $this->getMockFormTypeExtension(); @@ -129,7 +136,7 @@ public function testCreateBuilder() { $givenOptions = ['a' => 'a_custom', 'c' => 'c_custom']; $resolvedOptions = ['a' => 'a_custom', 'b' => 'b_default', 'c' => 'c_custom', 'd' => 'd_default']; - $optionsResolver = $this->getMockBuilder(OptionsResolver::class)->getMock(); + $optionsResolver = $this->createMock(OptionsResolver::class); $this->resolvedType = $this->getMockBuilder(ResolvedFormType::class) ->setConstructorArgs([$this->type, [$this->extension1, $this->extension2], $this->parentResolvedType]) @@ -157,7 +164,7 @@ public function testCreateBuilderWithDataClassOption() { $givenOptions = ['data_class' => 'Foo']; $resolvedOptions = ['data_class' => \stdClass::class]; - $optionsResolver = $this->getMockBuilder(OptionsResolver::class)->getMock(); + $optionsResolver = $this->createMock(OptionsResolver::class); $this->resolvedType = $this->getMockBuilder(ResolvedFormType::class) ->setConstructorArgs([$this->type, [$this->extension1, $this->extension2], $this->parentResolvedType]) @@ -183,7 +190,7 @@ public function testCreateBuilderWithDataClassOption() public function testFailsCreateBuilderOnInvalidFormOptionsResolution() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\MissingOptionsException::class); + $this->expectException(MissingOptionsException::class); $this->expectExceptionMessage('An error has occurred resolving the options of the form "Symfony\Component\Form\Extension\Core\Type\HiddenType": The required option "foo" is missing.'); $optionsResolver = (new OptionsResolver()) ->setRequired('foo') @@ -219,7 +226,7 @@ public function testBuildForm() }; $options = ['a' => 'Foo', 'b' => 'Bar']; - $builder = $this->getMockBuilder(\Symfony\Component\Form\Test\FormBuilderInterface::class)->getMock(); + $builder = $this->createMock(FormBuilderInterface::class); // First the form is built for the super type $this->parentType->expects($this->once()) @@ -249,30 +256,30 @@ public function testBuildForm() public function testCreateView() { - $form = new Form($this->getMockBuilder(FormConfigInterface::class)->getMock()); + $form = new Form($this->createMock(FormConfigInterface::class)); $view = $this->resolvedType->createView($form); - $this->assertInstanceOf(\Symfony\Component\Form\FormView::class, $view); + $this->assertInstanceOf(FormView::class, $view); $this->assertNull($view->parent); } public function testCreateViewWithParent() { - $form = new Form($this->getMockBuilder(FormConfigInterface::class)->getMock()); - $parentView = $this->getMockBuilder(\Symfony\Component\Form\FormView::class)->getMock(); + $form = new Form($this->createMock(FormConfigInterface::class)); + $parentView = $this->createMock(FormView::class); $view = $this->resolvedType->createView($form, $parentView); - $this->assertInstanceOf(\Symfony\Component\Form\FormView::class, $view); + $this->assertInstanceOf(FormView::class, $view); $this->assertSame($parentView, $view->parent); } public function testBuildView() { $options = ['a' => '1', 'b' => '2']; - $form = new Form($this->getMockBuilder(FormConfigInterface::class)->getMock()); - $view = $this->getMockBuilder(\Symfony\Component\Form\FormView::class)->getMock(); + $form = new Form($this->createMock(FormConfigInterface::class)); + $view = $this->createMock(FormView::class); $i = 0; @@ -313,8 +320,8 @@ public function testBuildView() public function testFinishView() { $options = ['a' => '1', 'b' => '2']; - $form = new Form($this->getMockBuilder(FormConfigInterface::class)->getMock()); - $view = $this->getMockBuilder(\Symfony\Component\Form\FormView::class)->getMock(); + $form = new Form($this->createMock(FormConfigInterface::class)); + $view = $this->createMock(FormView::class); $i = 0; @@ -392,11 +399,11 @@ private function getMockFormType($typeClass = 'Symfony\Component\Form\AbstractTy private function getMockFormTypeExtension(): MockObject { - return $this->getMockBuilder(\Symfony\Component\Form\AbstractTypeExtension::class)->setMethods(['getExtendedType', 'configureOptions', 'finishView', 'buildView', 'buildForm'])->getMock(); + return $this->getMockBuilder(AbstractTypeExtension::class)->setMethods(['getExtendedType', 'configureOptions', 'finishView', 'buildView', 'buildForm'])->getMock(); } private function getMockFormFactory(): MockObject { - return $this->getMockBuilder(\Symfony\Component\Form\FormFactoryInterface::class)->getMock(); + return $this->createMock(FormFactoryInterface::class); } } diff --git a/src/Symfony/Component/Form/Tests/SimpleFormTest.php b/src/Symfony/Component/Form/Tests/SimpleFormTest.php index a79591006c2b..8edfe15634f8 100644 --- a/src/Symfony/Component/Form/Tests/SimpleFormTest.php +++ b/src/Symfony/Component/Form/Tests/SimpleFormTest.php @@ -12,6 +12,9 @@ namespace Symfony\Component\Form\Tests; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Form\Exception\AlreadySubmittedException; +use Symfony\Component\Form\Exception\LogicException; +use Symfony\Component\Form\Exception\RuntimeException; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Form; use Symfony\Component\Form\FormConfigBuilder; @@ -19,6 +22,9 @@ use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\FormInterface; +use Symfony\Component\Form\FormView; +use Symfony\Component\Form\RequestHandlerInterface; +use Symfony\Component\Form\ResolvedFormTypeInterface; use Symfony\Component\Form\Tests\Fixtures\FixedDataTransformer; use Symfony\Component\Form\Tests\Fixtures\FixedFilterListener; use Symfony\Component\PropertyAccess\PropertyPath; @@ -174,7 +180,7 @@ public function testFalseIsConvertedToNull() public function testSubmitThrowsExceptionIfAlreadySubmitted() { - $this->expectException(\Symfony\Component\Form\Exception\AlreadySubmittedException::class); + $this->expectException(AlreadySubmittedException::class); $this->form->submit([]); $this->form->submit([]); } @@ -366,7 +372,7 @@ public function testHasNoErrors() public function testSetParentThrowsExceptionIfAlreadySubmitted() { - $this->expectException(\Symfony\Component\Form\Exception\AlreadySubmittedException::class); + $this->expectException(AlreadySubmittedException::class); $this->form->submit([]); $this->form->setParent($this->getBuilder('parent')->getForm()); } @@ -386,7 +392,7 @@ public function testNotSubmitted() public function testSetDataThrowsExceptionIfAlreadySubmitted() { - $this->expectException(\Symfony\Component\Form\Exception\AlreadySubmittedException::class); + $this->expectException(AlreadySubmittedException::class); $this->form->submit([]); $this->form->setData(null); } @@ -721,8 +727,8 @@ public function testSubmitResetsErrors() public function testCreateView() { - $type = $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormTypeInterface::class)->getMock(); - $view = $this->getMockBuilder(\Symfony\Component\Form\FormView::class)->getMock(); + $type = $this->createMock(ResolvedFormTypeInterface::class); + $view = $this->createMock(FormView::class); $form = $this->getBuilder()->setType($type)->getForm(); $type->expects($this->once()) @@ -735,11 +741,11 @@ public function testCreateView() public function testCreateViewWithParent() { - $type = $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormTypeInterface::class)->getMock(); - $view = $this->getMockBuilder(\Symfony\Component\Form\FormView::class)->getMock(); - $parentType = $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormTypeInterface::class)->getMock(); + $type = $this->createMock(ResolvedFormTypeInterface::class); + $view = $this->createMock(FormView::class); + $parentType = $this->createMock(ResolvedFormTypeInterface::class); $parentForm = $this->getBuilder()->setType($parentType)->getForm(); - $parentView = $this->getMockBuilder(\Symfony\Component\Form\FormView::class)->getMock(); + $parentView = $this->createMock(FormView::class); $form = $this->getBuilder()->setType($type)->getForm(); $form->setParent($parentForm); @@ -757,9 +763,9 @@ public function testCreateViewWithParent() public function testCreateViewWithExplicitParent() { - $type = $this->getMockBuilder(\Symfony\Component\Form\ResolvedFormTypeInterface::class)->getMock(); - $view = $this->getMockBuilder(\Symfony\Component\Form\FormView::class)->getMock(); - $parentView = $this->getMockBuilder(\Symfony\Component\Form\FormView::class)->getMock(); + $type = $this->createMock(ResolvedFormTypeInterface::class); + $view = $this->createMock(FormView::class); + $parentView = $this->createMock(FormView::class); $form = $this->getBuilder()->setType($type)->getForm(); $type->expects($this->once()) @@ -787,7 +793,7 @@ public function testSetNullParentWorksWithEmptyName() public function testFormCannotHaveEmptyNameNotInRootLevel() { - $this->expectException(\Symfony\Component\Form\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('A form with an empty name cannot have a parent form.'); $this->getBuilder() ->setCompound(true) @@ -882,7 +888,7 @@ public function testViewDataMayBeObjectIfDataClassIsNull() public function testViewDataMayBeArrayAccessIfDataClassIsNull() { - $arrayAccess = $this->getMockBuilder(\ArrayAccess::class)->getMock(); + $arrayAccess = $this->createMock(\ArrayAccess::class); $config = new FormConfigBuilder('name', null, $this->dispatcher); $config->addViewTransformer(new FixedDataTransformer([ '' => '', @@ -897,7 +903,7 @@ public function testViewDataMayBeArrayAccessIfDataClassIsNull() public function testViewDataMustBeObjectIfDataClassIsSet() { - $this->expectException(\Symfony\Component\Form\Exception\LogicException::class); + $this->expectException(LogicException::class); $config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher); $config->addViewTransformer(new FixedDataTransformer([ '' => '', @@ -910,7 +916,7 @@ public function testViewDataMustBeObjectIfDataClassIsSet() public function testSetDataCannotInvokeItself() { - $this->expectException(\Symfony\Component\Form\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('A cycle was detected. Listeners to the PRE_SET_DATA event must not call setData(). You should call setData() on the FormEvent object instead.'); // Cycle detection to prevent endless loops $config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher); @@ -944,7 +950,7 @@ public function testSubmittingWrongDataIsIgnored() public function testHandleRequestForwardsToRequestHandler() { - $handler = $this->getMockBuilder(\Symfony\Component\Form\RequestHandlerInterface::class)->getMock(); + $handler = $this->createMock(RequestHandlerInterface::class); $form = $this->getBuilder() ->setRequestHandler($handler) @@ -982,7 +988,7 @@ public function testFormInheritsParentData() public function testInheritDataDisallowsSetData() { - $this->expectException(\Symfony\Component\Form\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $form = $this->getBuilder() ->setInheritData(true) ->getForm(); @@ -992,7 +998,7 @@ public function testInheritDataDisallowsSetData() public function testGetDataRequiresParentToBeSetIfInheritData() { - $this->expectException(\Symfony\Component\Form\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $form = $this->getBuilder() ->setInheritData(true) ->getForm(); @@ -1002,7 +1008,7 @@ public function testGetDataRequiresParentToBeSetIfInheritData() public function testGetNormDataRequiresParentToBeSetIfInheritData() { - $this->expectException(\Symfony\Component\Form\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $form = $this->getBuilder() ->setInheritData(true) ->getForm(); @@ -1012,7 +1018,7 @@ public function testGetNormDataRequiresParentToBeSetIfInheritData() public function testGetViewDataRequiresParentToBeSetIfInheritData() { - $this->expectException(\Symfony\Component\Form\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $form = $this->getBuilder() ->setInheritData(true) ->getForm(); @@ -1062,7 +1068,7 @@ public function testInitializeSetsDefaultData() public function testInitializeFailsIfParent() { - $this->expectException(\Symfony\Component\Form\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $parent = $this->getBuilder()->setRequired(false)->getForm(); $child = $this->getBuilder()->setRequired(true)->getForm(); @@ -1073,7 +1079,7 @@ public function testInitializeFailsIfParent() public function testCannotCallGetDataInPreSetDataListenerIfDataHasNotAlreadyBeenSet() { - $this->expectException(\Symfony\Component\Form\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('A cycle was detected. Listeners to the PRE_SET_DATA event must not call getData() if the form data has not already been set. You should call getData() on the FormEvent object instead.'); $config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher); $config->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { @@ -1086,7 +1092,7 @@ public function testCannotCallGetDataInPreSetDataListenerIfDataHasNotAlreadyBeen public function testCannotCallGetNormDataInPreSetDataListener() { - $this->expectException(\Symfony\Component\Form\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('A cycle was detected. Listeners to the PRE_SET_DATA event must not call getNormData() if the form data has not already been set.'); $config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher); $config->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { @@ -1099,7 +1105,7 @@ public function testCannotCallGetNormDataInPreSetDataListener() public function testCannotCallGetViewDataInPreSetDataListener() { - $this->expectException(\Symfony\Component\Form\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('A cycle was detected. Listeners to the PRE_SET_DATA event must not call getViewData() if the form data has not already been set.'); $config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher); $config->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { diff --git a/src/Symfony/Component/HttpClient/Tests/MockHttpClientTest.php b/src/Symfony/Component/HttpClient/Tests/MockHttpClientTest.php index 17e1dd1c3d21..27cc87f0ccfb 100644 --- a/src/Symfony/Component/HttpClient/Tests/MockHttpClientTest.php +++ b/src/Symfony/Component/HttpClient/Tests/MockHttpClientTest.php @@ -137,7 +137,7 @@ protected function getHttpClient(string $testCase): HttpClientInterface break; case 'testDnsError': - $mock = $this->getMockBuilder(ResponseInterface::class)->getMock(); + $mock = $this->createMock(ResponseInterface::class); $mock->expects($this->any()) ->method('getStatusCode') ->willThrowException(new TransportException('DSN error')); @@ -160,7 +160,7 @@ protected function getHttpClient(string $testCase): HttpClientInterface break; case 'testTimeoutOnAccess': - $mock = $this->getMockBuilder(ResponseInterface::class)->getMock(); + $mock = $this->createMock(ResponseInterface::class); $mock->expects($this->any()) ->method('getHeaders') ->willThrowException(new TransportException('Timeout')); @@ -227,7 +227,7 @@ protected function getHttpClient(string $testCase): HttpClientInterface break; case 'testMaxDuration': - $mock = $this->getMockBuilder(ResponseInterface::class)->getMock(); + $mock = $this->createMock(ResponseInterface::class); $mock->expects($this->any()) ->method('getContent') ->willReturnCallback(static function (): void { diff --git a/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php b/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php index 949d8afcff85..20d09e3376e6 100755 --- a/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php +++ b/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php @@ -21,7 +21,7 @@ class TraceableHttpClientTest extends TestCase { public function testItTracesRequest() { - $httpClient = $this->getMockBuilder(HttpClientInterface::class)->getMock(); + $httpClient = $this->createMock(HttpClientInterface::class); $httpClient ->expects($this->once()) ->method('request') diff --git a/src/Symfony/Component/HttpFoundation/Tests/File/FileTest.php b/src/Symfony/Component/HttpFoundation/Tests/File/FileTest.php index 9b8272633c80..656333b377f5 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/File/FileTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/File/FileTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\File; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException; use Symfony\Component\HttpFoundation\File\File; /** @@ -41,7 +42,7 @@ public function testGuessExtensionIsBasedOnMimeType() public function testConstructWhenFileNotExists() { - $this->expectException(\Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException::class); + $this->expectException(FileNotFoundException::class); new File(__DIR__.'/Fixtures/not_here'); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/File/MimeType/MimeTypeTest.php b/src/Symfony/Component/HttpFoundation/Tests/File/MimeType/MimeTypeTest.php index ca369a01dfbc..bbc74e74a697 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/File/MimeType/MimeTypeTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/File/MimeType/MimeTypeTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\HttpFoundation\Tests\File\MimeType; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException; +use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException; use Symfony\Component\HttpFoundation\File\MimeType\FileBinaryMimeTypeGuesser; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser; @@ -39,7 +41,7 @@ public function testGuessImageWithoutExtension() public function testGuessImageWithDirectory() { - $this->expectException(\Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException::class); + $this->expectException(FileNotFoundException::class); MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/directory'); } @@ -68,7 +70,7 @@ public function testGuessWithDuplicatedFileType() public function testGuessWithIncorrectPath() { - $this->expectException(\Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException::class); + $this->expectException(FileNotFoundException::class); MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/not_here'); } @@ -87,7 +89,7 @@ public function testGuessWithNonReadablePath() @chmod($path, 0333); if ('0333' == substr(sprintf('%o', fileperms($path)), -4)) { - $this->expectException(\Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException::class); + $this->expectException(AccessDeniedException::class); MimeTypeGuesser::getInstance()->guess($path); } else { $this->markTestSkipped('Can not verify chmod operations, change of file permissions failed'); diff --git a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php index d95bba8fcdec..12ce2203e83b 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException; use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Session\Session; @@ -1087,7 +1088,7 @@ public function getClientIpsProvider() */ public function testGetClientIpsWithConflictingHeaders($httpForwarded, $httpXForwardedFor) { - $this->expectException(\Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException::class); + $this->expectException(ConflictingHeadersException::class); $request = new Request(); $server = [ diff --git a/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php b/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php index 23ac307daac9..f26302eef112 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php @@ -946,7 +946,7 @@ public function testSettersAreChainable() public function testNoDeprecationsAreTriggered() { new DefaultResponse(); - $this->getMockBuilder(Response::class)->getMock(); + $this->createMock(Response::class); // we just need to ensure that subclasses of Response can be created without any deprecations // being triggered if the subclass does not override any final methods diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/SessionTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/SessionTest.php index d54a419d753a..a2309508c9cd 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/SessionTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/SessionTest.php @@ -14,8 +14,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; +use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\SessionBagProxy; +use Symfony\Component\HttpFoundation\Session\Storage\MetadataBag; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; /** @@ -212,7 +214,7 @@ public function testGetId() public function testGetFlashBag() { - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface::class, $this->session->getFlashBag()); + $this->assertInstanceOf(FlashBagInterface::class, $this->session->getFlashBag()); } public function testGetIterator() @@ -241,7 +243,7 @@ public function testGetCount() public function testGetMeta() { - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\Session\Storage\MetadataBag::class, $this->session->getMetadataBag()); + $this->assertInstanceOf(MetadataBag::class, $this->session->getMetadataBag()); } public function testIsEmpty() diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php index c605607cb1e4..2663fba6b4b6 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php @@ -38,7 +38,7 @@ protected function setUp(): void $this->markTestSkipped('Tests can only be run with memcached extension 2.1.0 or lower, or 3.0.0b1 or higher'); } - $this->memcached = $this->getMockBuilder(\Memcached::class)->getMock(); + $this->memcached = $this->createMock(\Memcached::class); $this->storage = new MemcachedSessionHandler( $this->memcached, ['prefix' => self::PREFIX, 'expiretime' => self::TTL] diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index b5fb7067bdae..c73118091636 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -131,7 +131,7 @@ public function testReadWriteReadWithNullByte() public function testReadConvertsStreamToString() { $pdo = new MockPdo('pgsql'); - $pdo->prepareResult = $this->getMockBuilder(\PDOStatement::class)->getMock(); + $pdo->prepareResult = $this->createMock(\PDOStatement::class); $content = 'foobar'; $stream = $this->createStream($content); @@ -152,8 +152,8 @@ public function testReadLockedConvertsStreamToString() } $pdo = new MockPdo('pgsql'); - $selectStmt = $this->getMockBuilder(\PDOStatement::class)->getMock(); - $insertStmt = $this->getMockBuilder(\PDOStatement::class)->getMock(); + $selectStmt = $this->createMock(\PDOStatement::class); + $insertStmt = $this->createMock(\PDOStatement::class); $pdo->prepareResult = function ($statement) use ($selectStmt, $insertStmt) { return 0 === strpos($statement, 'INSERT') ? $insertStmt : $selectStmt; diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php index 1a632b248fb4..353b1a02ec99 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php @@ -19,7 +19,7 @@ class StrictSessionHandlerTest extends TestCase { public function testOpen() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('open') ->with('path', 'name')->willReturn(true); $proxy = new StrictSessionHandler($handler); @@ -31,7 +31,7 @@ public function testOpen() public function testCloseSession() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('close') ->willReturn(true); $proxy = new StrictSessionHandler($handler); @@ -41,7 +41,7 @@ public function testCloseSession() public function testValidateIdOK() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('read') ->with('id')->willReturn('data'); $proxy = new StrictSessionHandler($handler); @@ -51,7 +51,7 @@ public function testValidateIdOK() public function testValidateIdKO() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('read') ->with('id')->willReturn(''); $proxy = new StrictSessionHandler($handler); @@ -61,7 +61,7 @@ public function testValidateIdKO() public function testRead() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('read') ->with('id')->willReturn('data'); $proxy = new StrictSessionHandler($handler); @@ -71,7 +71,7 @@ public function testRead() public function testReadWithValidateIdOK() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('read') ->with('id')->willReturn('data'); $proxy = new StrictSessionHandler($handler); @@ -82,7 +82,7 @@ public function testReadWithValidateIdOK() public function testReadWithValidateIdMismatch() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->exactly(2))->method('read') ->withConsecutive(['id1'], ['id2']) ->will($this->onConsecutiveCalls('data1', 'data2')); @@ -94,7 +94,7 @@ public function testReadWithValidateIdMismatch() public function testUpdateTimestamp() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('write') ->with('id', 'data')->willReturn(true); $proxy = new StrictSessionHandler($handler); @@ -104,7 +104,7 @@ public function testUpdateTimestamp() public function testWrite() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('write') ->with('id', 'data')->willReturn(true); $proxy = new StrictSessionHandler($handler); @@ -114,7 +114,7 @@ public function testWrite() public function testWriteEmptyNewSession() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('read') ->with('id')->willReturn(''); $handler->expects($this->never())->method('write'); @@ -128,7 +128,7 @@ public function testWriteEmptyNewSession() public function testWriteEmptyExistingSession() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('read') ->with('id')->willReturn('data'); $handler->expects($this->never())->method('write'); @@ -141,7 +141,7 @@ public function testWriteEmptyExistingSession() public function testDestroy() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('destroy') ->with('id')->willReturn(true); $proxy = new StrictSessionHandler($handler); @@ -151,7 +151,7 @@ public function testDestroy() public function testDestroyNewSession() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('read') ->with('id')->willReturn(''); $handler->expects($this->once())->method('destroy')->willReturn(true); @@ -163,7 +163,7 @@ public function testDestroyNewSession() public function testDestroyNonEmptyNewSession() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('read') ->with('id')->willReturn(''); $handler->expects($this->once())->method('write') @@ -179,7 +179,7 @@ public function testDestroyNonEmptyNewSession() public function testGc() { - $handler = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $handler = $this->createMock(\SessionHandlerInterface::class); $handler->expects($this->once())->method('gc') ->with(123)->willReturn(true); $proxy = new StrictSessionHandler($handler); diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php index 96792fd12850..e323fc3987ea 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php @@ -36,7 +36,7 @@ class SessionHandlerProxyTest extends TestCase protected function setUp(): void { - $this->mock = $this->getMockBuilder(\SessionHandlerInterface::class)->getMock(); + $this->mock = $this->createMock(\SessionHandlerInterface::class); $this->proxy = new SessionHandlerProxy($this->mock); } @@ -127,7 +127,7 @@ public function testGc() */ public function testValidateId() { - $mock = $this->getMockBuilder(TestSessionHandler::class)->getMock(); + $mock = $this->createMock(TestSessionHandler::class); $mock->expects($this->once()) ->method('validateId'); @@ -142,7 +142,7 @@ public function testValidateId() */ public function testUpdateTimestamp() { - $mock = $this->getMockBuilder(TestSessionHandler::class)->getMock(); + $mock = $this->createMock(TestSessionHandler::class); $mock->expects($this->once()) ->method('updateTimestamp') ->willReturn(false); diff --git a/src/Symfony/Component/HttpKernel/Tests/CacheClearer/ChainCacheClearerTest.php b/src/Symfony/Component/HttpKernel/Tests/CacheClearer/ChainCacheClearerTest.php index a0b4bd8c41cb..80c1b576be3e 100644 --- a/src/Symfony/Component/HttpKernel/Tests/CacheClearer/ChainCacheClearerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/CacheClearer/ChainCacheClearerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests\CacheClearer; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface; use Symfony\Component\HttpKernel\CacheClearer\ChainCacheClearer; class ChainCacheClearerTest extends TestCase @@ -41,6 +42,6 @@ public function testInjectClearersInConstructor() protected function getMockClearer() { - return $this->getMockBuilder(\Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface::class)->getMock(); + return $this->createMock(CacheClearerInterface::class); } } diff --git a/src/Symfony/Component/HttpKernel/Tests/CacheClearer/Psr6CacheClearerTest.php b/src/Symfony/Component/HttpKernel/Tests/CacheClearer/Psr6CacheClearerTest.php index c7c683428e7b..0c6f1543acfd 100644 --- a/src/Symfony/Component/HttpKernel/Tests/CacheClearer/Psr6CacheClearerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/CacheClearer/Psr6CacheClearerTest.php @@ -19,7 +19,7 @@ class Psr6CacheClearerTest extends TestCase { public function testClearPoolsInjectedInConstructor() { - $pool = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock(); + $pool = $this->createMock(CacheItemPoolInterface::class); $pool ->expects($this->once()) ->method('clear'); @@ -29,7 +29,7 @@ public function testClearPoolsInjectedInConstructor() public function testClearPool() { - $pool = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock(); + $pool = $this->createMock(CacheItemPoolInterface::class); $pool ->expects($this->once()) ->method('clear'); diff --git a/src/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerAggregateTest.php b/src/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerAggregateTest.php index cf9493a2950e..c34cc9c400c3 100644 --- a/src/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerAggregateTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerAggregateTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerAggregate; +use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; class CacheWarmerAggregateTest extends TestCase { @@ -30,7 +31,7 @@ public static function tearDownAfterClass(): void public function testInjectWarmersUsingConstructor() { - $warmer = $this->getCacheWarmerMock(); + $warmer = $this->createMock(CacheWarmerInterface::class); $warmer ->expects($this->once()) ->method('warmUp'); @@ -40,7 +41,7 @@ public function testInjectWarmersUsingConstructor() public function testWarmupDoesCallWarmupOnOptionalWarmersWhenEnableOptionalWarmersIsEnabled() { - $warmer = $this->getCacheWarmerMock(); + $warmer = $this->createMock(CacheWarmerInterface::class); $warmer ->expects($this->never()) ->method('isOptional'); @@ -55,7 +56,7 @@ public function testWarmupDoesCallWarmupOnOptionalWarmersWhenEnableOptionalWarme public function testWarmupDoesNotCallWarmupOnOptionalWarmersWhenEnableOptionalWarmersIsNotEnabled() { - $warmer = $this->getCacheWarmerMock(); + $warmer = $this->createMock(CacheWarmerInterface::class); $warmer ->expects($this->once()) ->method('isOptional') @@ -67,13 +68,4 @@ public function testWarmupDoesNotCallWarmupOnOptionalWarmersWhenEnableOptionalWa $aggregate = new CacheWarmerAggregate([$warmer]); $aggregate->warmUp(self::$cacheDir); } - - protected function getCacheWarmerMock() - { - $warmer = $this->getMockBuilder(\Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - return $warmer; - } } diff --git a/src/Symfony/Component/HttpKernel/Tests/Config/FileLocatorTest.php b/src/Symfony/Component/HttpKernel/Tests/Config/FileLocatorTest.php index d992286752b9..e70e49e83c19 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Config/FileLocatorTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Config/FileLocatorTest.php @@ -13,12 +13,13 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpKernel\Config\FileLocator; +use Symfony\Component\HttpKernel\KernelInterface; class FileLocatorTest extends TestCase { public function testLocate() { - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel ->expects($this->atLeastOnce()) ->method('locateResource') @@ -39,7 +40,7 @@ public function testLocate() */ public function testLocateWithGlobalResourcePath() { - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel ->expects($this->atLeastOnce()) ->method('locateResource') diff --git a/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/NotTaggedControllerValueResolverTest.php b/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/NotTaggedControllerValueResolverTest.php index efb7322efa03..3cf2f0f18562 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/NotTaggedControllerValueResolverTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/NotTaggedControllerValueResolverTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests\Controller\ArgumentResolver; use PHPUnit\Framework\TestCase; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\ServiceLocator; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Controller\ArgumentResolver\NotTaggedControllerValueResolver; @@ -55,7 +56,7 @@ public function testDoNotSupportEmptyController() public function testController() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Could not resolve argument $dummy of "App\Controller\Mine::method()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?'); $resolver = new NotTaggedControllerValueResolver(new ServiceLocator([])); $argument = new ArgumentMetadata('dummy', \stdClass::class, false, false, null); @@ -66,7 +67,7 @@ public function testController() public function testControllerWithATrailingBackSlash() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Could not resolve argument $dummy of "App\Controller\Mine::method()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?'); $resolver = new NotTaggedControllerValueResolver(new ServiceLocator([])); $argument = new ArgumentMetadata('dummy', \stdClass::class, false, false, null); @@ -77,7 +78,7 @@ public function testControllerWithATrailingBackSlash() public function testControllerWithMethodNameStartUppercase() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Could not resolve argument $dummy of "App\Controller\Mine::method()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?'); $resolver = new NotTaggedControllerValueResolver(new ServiceLocator([])); $argument = new ArgumentMetadata('dummy', \stdClass::class, false, false, null); @@ -88,7 +89,7 @@ public function testControllerWithMethodNameStartUppercase() public function testControllerNameIsAnArray() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Could not resolve argument $dummy of "App\Controller\Mine::method()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?'); $resolver = new NotTaggedControllerValueResolver(new ServiceLocator([])); $argument = new ArgumentMetadata('dummy', \stdClass::class, false, false, null); diff --git a/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/ServiceValueResolverTest.php b/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/ServiceValueResolverTest.php index 743eefa3e50a..69b9511c0523 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/ServiceValueResolverTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/ServiceValueResolverTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\ServiceLocator; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Controller\ArgumentResolver\ServiceValueResolver; @@ -107,7 +108,7 @@ public function testControllerNameIsAnArray() public function testErrorIsTruncated() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Cannot autowire argument $dummy of "Symfony\Component\HttpKernel\Tests\Controller\ArgumentResolver\DummyController::index()": it references class "Symfony\Component\HttpKernel\Tests\Controller\ArgumentResolver\DummyService" but no such service exists.'); $container = new ContainerBuilder(); $container->addCompilerPass(new RegisterControllerArgumentLocatorsPass()); diff --git a/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolverTest.php b/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolverTest.php index da521ff20426..40638b4fe6f8 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolverTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolverTest.php @@ -177,7 +177,7 @@ public function testGetArgumentWithoutArray() { $this->expectException(\InvalidArgumentException::class); $factory = new ArgumentMetadataFactory(); - $valueResolver = $this->getMockBuilder(ArgumentValueResolverInterface::class)->getMock(); + $valueResolver = $this->createMock(ArgumentValueResolverInterface::class); $resolver = new ArgumentResolver($factory, [$valueResolver]); $valueResolver->expects($this->any())->method('supports')->willReturn(true); @@ -241,7 +241,7 @@ public function testGetSessionArgumentsWithExtendedSession() public function testGetSessionArgumentsWithInterface() { - $session = $this->getMockBuilder(SessionInterface::class)->getMock(); + $session = $this->createMock(SessionInterface::class); $request = Request::create('/'); $request->setSession($session); $controller = [$this, 'controllerWithSessionInterface']; @@ -252,7 +252,7 @@ public function testGetSessionArgumentsWithInterface() public function testGetSessionMissMatchWithInterface() { $this->expectException(\RuntimeException::class); - $session = $this->getMockBuilder(SessionInterface::class)->getMock(); + $session = $this->createMock(SessionInterface::class); $request = Request::create('/'); $request->setSession($session); $controller = [$this, 'controllerWithExtendingSession']; diff --git a/src/Symfony/Component/HttpKernel/Tests/Controller/ContainerControllerResolverTest.php b/src/Symfony/Component/HttpKernel/Tests/Controller/ContainerControllerResolverTest.php index 7f4564688c42..1c239fc4c035 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Controller/ContainerControllerResolverTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Controller/ContainerControllerResolverTest.php @@ -153,7 +153,7 @@ public function testExceptionWhenUsingRemovedControllerServiceWithClassNameAsNam { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Controller "Symfony\Component\HttpKernel\Tests\Controller\ControllerTestService" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?'); - $container = $this->getMockBuilder(Container::class)->getMock(); + $container = $this->createMock(Container::class); $container->expects($this->once()) ->method('has') ->with(ControllerTestService::class) @@ -177,7 +177,7 @@ public function testExceptionWhenUsingRemovedControllerService() { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Controller "app.my_controller" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?'); - $container = $this->getMockBuilder(Container::class)->getMock(); + $container = $this->createMock(Container::class); $container->expects($this->once()) ->method('has') ->with('app.my_controller') @@ -232,7 +232,7 @@ protected function createControllerResolver(LoggerInterface $logger = null, Cont protected function createMockContainer() { - return $this->getMockBuilder(ContainerInterface::class)->getMock(); + return $this->createMock(ContainerInterface::class); } } diff --git a/src/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php b/src/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php index 834f925c43b2..2afcfe4b4edc 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php @@ -20,7 +20,7 @@ class ControllerResolverTest extends TestCase { public function testGetControllerWithoutControllerParameter() { - $logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $logger->expects($this->once())->method('warning')->with('Unable to look for the controller as the "_controller" parameter is missing.'); $resolver = $this->createControllerResolver($logger); diff --git a/src/Symfony/Component/HttpKernel/Tests/Controller/ErrorControllerTest.php b/src/Symfony/Component/HttpKernel/Tests/Controller/ErrorControllerTest.php index fadd820ea66c..1b3a833578f4 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Controller/ErrorControllerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Controller/ErrorControllerTest.php @@ -27,7 +27,7 @@ class ErrorControllerTest extends TestCase */ public function testInvokeController(Request $request, \Exception $exception, int $statusCode, string $content) { - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $errorRenderer = new HtmlErrorRenderer(); $controller = new ErrorController($kernel, null, $errorRenderer); $response = $controller($exception); @@ -67,7 +67,7 @@ public function testPreviewController() $_controller = 'error_controller'; $code = 404; - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $kernel ->expects($this->once()) ->method('handle') diff --git a/src/Symfony/Component/HttpKernel/Tests/DataCollector/DumpDataCollectorTest.php b/src/Symfony/Component/HttpKernel/Tests/DataCollector/DumpDataCollectorTest.php index a40a48227815..c69166bf0924 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DataCollector/DumpDataCollectorTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DataCollector/DumpDataCollectorTest.php @@ -62,7 +62,7 @@ public function testDumpWithServerConnection() $data = new Data([[123]]); // Server is up, server dumper is used - $serverDumper = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); + $serverDumper = $this->createMock(Connection::class); $serverDumper->expects($this->once())->method('write')->willReturn(true); $collector = new DumpDataCollector(null, null, null, null, $serverDumper); diff --git a/src/Symfony/Component/HttpKernel/Tests/DataCollector/RequestDataCollectorTest.php b/src/Symfony/Component/HttpKernel/Tests/DataCollector/RequestDataCollectorTest.php index bb29b4ba52fb..e81a6e5b57cb 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DataCollector/RequestDataCollectorTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DataCollector/RequestDataCollectorTest.php @@ -21,6 +21,7 @@ use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface; +use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector; use Symfony\Component\HttpKernel\Event\ControllerEvent; use Symfony\Component\HttpKernel\Event\ResponseEvent; @@ -203,7 +204,7 @@ public function testItAddsRedirectedAttributesWhenRequestContainsSpecificCookie( 'sf_redirect' => '{}', ]); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $c = new RequestDataCollector(); $c->onKernelResponse(new ResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, $this->createResponse())); @@ -288,8 +289,8 @@ protected function createResponse() */ protected function injectController($collector, $controller, $request) { - $resolver = $this->getMockBuilder(\Symfony\Component\HttpKernel\Controller\ControllerResolverInterface::class)->getMock(); - $httpKernel = new HttpKernel(new EventDispatcher(), $resolver, null, $this->getMockBuilder(ArgumentResolverInterface::class)->getMock()); + $resolver = $this->createMock(ControllerResolverInterface::class); + $httpKernel = new HttpKernel(new EventDispatcher(), $resolver, null, $this->createMock(ArgumentResolverInterface::class)); $event = new ControllerEvent($httpKernel, $controller, $request, HttpKernelInterface::MASTER_REQUEST); $collector->onKernelController($event); } diff --git a/src/Symfony/Component/HttpKernel/Tests/DataCollector/TimeDataCollectorTest.php b/src/Symfony/Component/HttpKernel/Tests/DataCollector/TimeDataCollectorTest.php index ab231ac4c5a4..0496f1a3d166 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DataCollector/TimeDataCollectorTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DataCollector/TimeDataCollectorTest.php @@ -15,6 +15,7 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\DataCollector\TimeDataCollector; +use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Stopwatch\Stopwatch; /** @@ -43,7 +44,7 @@ public function testCollect() $c->collect($request, new Response()); $this->assertEquals(0, $c->getStartTime()); - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\KernelInterface::class)->getMock(); + $kernel = $this->createMock(KernelInterface::class); $kernel->expects($this->once())->method('getStartTime')->willReturn(123456.0); $c = new TimeDataCollector($kernel); diff --git a/src/Symfony/Component/HttpKernel/Tests/Debug/TraceableEventDispatcherTest.php b/src/Symfony/Component/HttpKernel/Tests/Debug/TraceableEventDispatcherTest.php index c4d42ec64866..2fb050dafd9f 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Debug/TraceableEventDispatcherTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Debug/TraceableEventDispatcherTest.php @@ -17,6 +17,8 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface; +use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; use Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher; use Symfony\Component\HttpKernel\HttpKernel; use Symfony\Component\Stopwatch\Stopwatch; @@ -110,9 +112,9 @@ public function testListenerCanRemoveItselfWhenExecuted() protected function getHttpKernel($dispatcher, $controller) { - $controllerResolver = $this->getMockBuilder(\Symfony\Component\HttpKernel\Controller\ControllerResolverInterface::class)->getMock(); + $controllerResolver = $this->createMock(ControllerResolverInterface::class); $controllerResolver->expects($this->once())->method('getController')->willReturn($controller); - $argumentResolver = $this->getMockBuilder(\Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface::class)->getMock(); + $argumentResolver = $this->createMock(ArgumentResolverInterface::class); $argumentResolver->expects($this->once())->method('getArguments')->willReturn([]); return new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver); diff --git a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/LazyLoadingFragmentHandlerTest.php b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/LazyLoadingFragmentHandlerTest.php index 493178d47016..c8db5e55e9b0 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/LazyLoadingFragmentHandlerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/LazyLoadingFragmentHandlerTest.php @@ -12,22 +12,25 @@ namespace Symfony\Component\HttpKernel\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Psr\Container\ContainerInterface; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\DependencyInjection\LazyLoadingFragmentHandler; +use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface; class LazyLoadingFragmentHandlerTest extends TestCase { public function testRender() { - $renderer = $this->getMockBuilder(\Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface::class)->getMock(); + $renderer = $this->createMock(FragmentRendererInterface::class); $renderer->expects($this->once())->method('getName')->willReturn('foo'); $renderer->expects($this->any())->method('render')->willReturn(new Response()); - $requestStack = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestStack::class)->getMock(); + $requestStack = $this->createMock(RequestStack::class); $requestStack->expects($this->any())->method('getCurrentRequest')->willReturn(Request::create('/')); - $container = $this->getMockBuilder(\Psr\Container\ContainerInterface::class)->getMock(); + $container = $this->createMock(ContainerInterface::class); $container->expects($this->once())->method('has')->with('foo')->willReturn(true); $container->expects($this->once())->method('get')->willReturn($renderer); diff --git a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php index 8a65b4ff38d9..c00e1849fc50 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php @@ -18,6 +18,7 @@ use Symfony\Component\DependencyInjection\ContainerAwareTrait; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ServiceLocator; use Symfony\Component\DependencyInjection\TypedReference; @@ -27,7 +28,7 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase { public function testInvalidClass() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Class "Symfony\Component\HttpKernel\Tests\DependencyInjection\NotFound" used for service "foo" cannot be found.'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -42,7 +43,7 @@ public function testInvalidClass() public function testNoAction() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Missing "action" attribute on tag "controller.service_arguments" {"argument":"bar"} for service "foo".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -57,7 +58,7 @@ public function testNoAction() public function testNoArgument() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Missing "argument" attribute on tag "controller.service_arguments" {"action":"fooAction"} for service "foo".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -72,7 +73,7 @@ public function testNoArgument() public function testNoService() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Missing "id" attribute on tag "controller.service_arguments" {"action":"fooAction","argument":"bar"} for service "foo".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -87,7 +88,7 @@ public function testNoService() public function testInvalidMethod() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid "action" attribute on tag "controller.service_arguments" for service "foo": no public "barAction()" method found on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -102,7 +103,7 @@ public function testInvalidMethod() public function testInvalidArgument() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid "controller.service_arguments" tag for service "foo": method "fooAction()" has no "baz" argument on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -197,7 +198,7 @@ public function testSkipSetContainer() public function testExceptionOnNonExistentTypeHint() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClass". Did you forget to add a use statement?'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -211,7 +212,7 @@ public function testExceptionOnNonExistentTypeHint() public function testExceptionOnNonExistentTypeHintDifferentNamespace() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassDifferentNamespaceController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Acme\NonExistentClass".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); diff --git a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/ResettableServicePassTest.php b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/ResettableServicePassTest.php index b28f90d3628c..4c110e3a2680 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/ResettableServicePassTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/ResettableServicePassTest.php @@ -6,6 +6,7 @@ use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\HttpKernel\DependencyInjection\ResettableServicePass; use Symfony\Component\HttpKernel\DependencyInjection\ServicesResetter; @@ -57,7 +58,7 @@ public function testCompilerPass() public function testMissingMethod() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Tag "kernel.reset" requires the "method" attribute to be set.'); $container = new ContainerBuilder(); $container->register(ResettableService::class) diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/AddRequestFormatsListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/AddRequestFormatsListenerTest.php index 6c4459fc2a70..def383185134 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/AddRequestFormatsListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/AddRequestFormatsListenerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests\EventListener; use PHPUnit\Framework\TestCase; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\EventListener\AddRequestFormatsListener; @@ -41,7 +42,7 @@ protected function tearDown(): void public function testIsAnEventSubscriber() { - $this->assertInstanceOf(\Symfony\Component\EventDispatcher\EventSubscriberInterface::class, $this->listener); + $this->assertInstanceOf(EventSubscriberInterface::class, $this->listener); } public function testRegisteredEvent() @@ -66,16 +67,12 @@ public function testSetAdditionalFormats() protected function getRequestMock() { - return $this->getMockBuilder(Request::class)->getMock(); + return $this->createMock(Request::class); } protected function getRequestEventMock(Request $request) { - $event = $this - ->getMockBuilder(RequestEvent::class) - ->disableOriginalConstructor() - ->getMock(); - + $event = $this->createMock(RequestEvent::class); $event->expects($this->any()) ->method('getRequest') ->willReturn($request); diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/DebugHandlersListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/DebugHandlersListenerTest.php index fb18d63fbec1..8d74b2c0ddee 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/DebugHandlersListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/DebugHandlersListenerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests\EventListener; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; use Symfony\Component\Console\Application; use Symfony\Component\Console\Command\Command; @@ -35,7 +36,7 @@ class DebugHandlersListenerTest extends TestCase { public function testConfigure() { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $userHandler = function () {}; $listener = new DebugHandlersListener($userHandler, $logger); $eHandler = new ErrorHandler(); @@ -67,7 +68,7 @@ public function testConfigureForHttpKernelWithNoTerminateWithException() $listener = new DebugHandlersListener(null); $eHandler = new ErrorHandler(); $event = new KernelEvent( - $this->getMockBuilder(HttpKernelInterface::class)->getMock(), + $this->createMock(HttpKernelInterface::class), Request::create('/'), HttpKernelInterface::MASTER_REQUEST ); @@ -91,7 +92,7 @@ public function testConsoleEvent() { $dispatcher = new EventDispatcher(); $listener = new DebugHandlersListener(null); - $app = $this->getMockBuilder(Application::class)->getMock(); + $app = $this->createMock(Application::class); $app->expects($this->once())->method('getHelperSet')->willReturn(new HelperSet()); $command = new Command(__FUNCTION__); $command->setApplication($app); diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/ErrorListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/ErrorListenerTest.php index 4428e3d1a616..2cd1091a7f4a 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/ErrorListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/ErrorListenerTest.php @@ -115,9 +115,9 @@ public function provider() public function testSubRequestFormat() { - $listener = new ErrorListener('foo', $this->getMockBuilder(LoggerInterface::class)->getMock()); + $listener = new ErrorListener('foo', $this->createMock(LoggerInterface::class)); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $kernel->expects($this->once())->method('handle')->willReturnCallback(function (Request $request) { return new Response($request->getRequestFormat()); }); @@ -135,12 +135,12 @@ public function testSubRequestFormat() public function testCSPHeaderIsRemoved() { $dispatcher = new EventDispatcher(); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $kernel->expects($this->once())->method('handle')->willReturnCallback(function (Request $request) { return new Response($request->getRequestFormat()); }); - $listener = new ErrorListener('foo', $this->getMockBuilder(LoggerInterface::class)->getMock(), true); + $listener = new ErrorListener('foo', $this->createMock(LoggerInterface::class), true); $dispatcher->addSubscriber($listener); diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/ExceptionListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/ExceptionListenerTest.php index 91ff62d906ca..6163f5b56e4f 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/ExceptionListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/ExceptionListenerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests\EventListener; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -112,9 +113,9 @@ public function provider() public function testSubRequestFormat() { - $listener = new ExceptionListener('foo', $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock()); + $listener = new ExceptionListener('foo', $this->createMock(LoggerInterface::class)); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $kernel->expects($this->once())->method('handle')->willReturnCallback(function (Request $request) { return new Response($request->getRequestFormat()); }); @@ -132,12 +133,12 @@ public function testSubRequestFormat() public function testCSPHeaderIsRemoved() { $dispatcher = new EventDispatcher(); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $kernel->expects($this->once())->method('handle')->willReturnCallback(function (Request $request) { return new Response($request->getRequestFormat()); }); - $listener = new ExceptionListener('foo', $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(), true); + $listener = new ExceptionListener('foo', $this->createMock(LoggerInterface::class), true); $dispatcher->addSubscriber($listener); diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/FragmentListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/FragmentListenerTest.php index e0b857debdfd..5720420dbf5c 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/FragmentListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/FragmentListenerTest.php @@ -15,6 +15,7 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\EventListener\FragmentListener; +use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\UriSigner; @@ -52,7 +53,7 @@ public function testOnlyTriggeredIfControllerWasNotDefinedYet() public function testAccessDeniedWithNonSafeMethods() { - $this->expectException(\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException::class); + $this->expectException(AccessDeniedHttpException::class); $request = Request::create('http://example.com/_fragment', 'POST'); $listener = new FragmentListener(new UriSigner('foo')); @@ -63,7 +64,7 @@ public function testAccessDeniedWithNonSafeMethods() public function testAccessDeniedWithWrongSignature() { - $this->expectException(\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException::class); + $this->expectException(AccessDeniedHttpException::class); $request = Request::create('http://example.com/_fragment', 'GET', [], [], [], ['REMOTE_ADDR' => '10.0.0.1']); $listener = new FragmentListener(new UriSigner('foo')); @@ -113,6 +114,6 @@ public function testRemovesPathWithControllerNotDefined() private function createRequestEvent(Request $request, $requestType = HttpKernelInterface::MASTER_REQUEST) { - return new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $request, $requestType); + return new RequestEvent($this->createMock(HttpKernelInterface::class), $request, $requestType); } } diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/LocaleAwareListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/LocaleAwareListenerTest.php index 0d14e5a9874f..20c9f9d8c9e4 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/LocaleAwareListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/LocaleAwareListenerTest.php @@ -28,7 +28,7 @@ class LocaleAwareListenerTest extends TestCase protected function setUp(): void { - $this->localeAwareService = $this->getMockBuilder(LocaleAwareInterface::class)->getMock(); + $this->localeAwareService = $this->createMock(LocaleAwareInterface::class); $this->requestStack = new RequestStack(); $this->listener = new LocaleAwareListener(new \ArrayIterator([$this->localeAwareService]), $this->requestStack); } @@ -110,7 +110,7 @@ public function testDefaultLocaleIsUsedOnExceptionsInOnKernelFinishRequest() private function createHttpKernel() { - return $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + return $this->createMock(HttpKernelInterface::class); } private function createRequest($locale) diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/LocaleListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/LocaleListenerTest.php index 705600d70e7c..186ce43b1d84 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/LocaleListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/LocaleListenerTest.php @@ -14,11 +14,14 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpKernel\Event\FinishRequestEvent; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\EventListener\LocaleListener; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Component\Routing\RequestContext; +use Symfony\Component\Routing\Router; class LocaleListenerTest extends TestCase { @@ -26,7 +29,7 @@ class LocaleListenerTest extends TestCase protected function setUp(): void { - $this->requestStack = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestStack::class)->disableOriginalConstructor()->getMock(); + $this->requestStack = $this->createMock(RequestStack::class); } public function testIsAnEventSubscriber() @@ -70,10 +73,10 @@ public function testLocaleFromRequestAttribute() public function testLocaleSetForRoutingContext() { // the request context is updated - $context = $this->getMockBuilder(\Symfony\Component\Routing\RequestContext::class)->getMock(); + $context = $this->createMock(RequestContext::class); $context->expects($this->once())->method('setParameter')->with('_locale', 'es'); - $router = $this->getMockBuilder(\Symfony\Component\Routing\Router::class)->setMethods(['getContext'])->disableOriginalConstructor()->getMock(); + $router = $this->getMockBuilder(Router::class)->setMethods(['getContext'])->disableOriginalConstructor()->getMock(); $router->expects($this->once())->method('getContext')->willReturn($context); $request = Request::create('/'); @@ -86,10 +89,10 @@ public function testLocaleSetForRoutingContext() public function testRouterResetWithParentRequestOnKernelFinishRequest() { // the request context is updated - $context = $this->getMockBuilder(\Symfony\Component\Routing\RequestContext::class)->getMock(); + $context = $this->createMock(RequestContext::class); $context->expects($this->once())->method('setParameter')->with('_locale', 'es'); - $router = $this->getMockBuilder(\Symfony\Component\Routing\Router::class)->setMethods(['getContext'])->disableOriginalConstructor()->getMock(); + $router = $this->getMockBuilder(Router::class)->setMethods(['getContext'])->disableOriginalConstructor()->getMock(); $router->expects($this->once())->method('getContext')->willReturn($context); $parentRequest = Request::create('/'); @@ -116,6 +119,6 @@ public function testRequestLocaleIsNotOverridden() private function getEvent(Request $request): RequestEvent { - return new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $request, HttpKernelInterface::MASTER_REQUEST); + return new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST); } } diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/ProfilerListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/ProfilerListenerTest.php index 4b076ef17d3e..8f7aca2a00c1 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/ProfilerListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/ProfilerListenerTest.php @@ -12,14 +12,18 @@ namespace Symfony\Component\HttpKernel\Tests\EventListener; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\HttpKernel\Event\ResponseEvent; use Symfony\Component\HttpKernel\Event\TerminateEvent; use Symfony\Component\HttpKernel\EventListener\ProfilerListener; use Symfony\Component\HttpKernel\Exception\HttpException; +use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\HttpKernel\Profiler\Profile; +use Symfony\Component\HttpKernel\Profiler\Profiler; class ProfilerListenerTest extends TestCase { @@ -30,27 +34,15 @@ public function testKernelTerminate() { $profile = new Profile('token'); - $profiler = $this->getMockBuilder(\Symfony\Component\HttpKernel\Profiler\Profiler::class) - ->disableOriginalConstructor() - ->getMock(); - + $profiler = $this->createMock(Profiler::class); $profiler->expects($this->once()) ->method('collect') ->willReturn($profile); - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\HttpKernelInterface::class)->getMock(); - - $masterRequest = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class) - ->disableOriginalConstructor() - ->getMock(); - - $subRequest = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class) - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Response::class) - ->disableOriginalConstructor() - ->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); + $masterRequest = $this->createMock(Request::class); + $subRequest = $this->createMock(Request::class); + $response = $this->createMock(Response::class); $requestStack = new RequestStack(); $requestStack->push($masterRequest); diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/ResponseListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/ResponseListenerTest.php index 31cfa38477e8..6c5af2a6dd21 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/ResponseListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/ResponseListenerTest.php @@ -32,7 +32,7 @@ protected function setUp(): void $listener = new ResponseListener('UTF-8'); $this->dispatcher->addListener(KernelEvents::RESPONSE, [$listener, 'onKernelResponse']); - $this->kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $this->kernel = $this->createMock(HttpKernelInterface::class); } protected function tearDown(): void diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php index 59e63deea890..cc46fd8db595 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests\EventListener; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; @@ -22,9 +23,12 @@ use Symfony\Component\HttpKernel\EventListener\ErrorListener; use Symfony\Component\HttpKernel\EventListener\RouterListener; use Symfony\Component\HttpKernel\EventListener\ValidateRequestListener; +use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\HttpKernel; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\Routing\Exception\NoConfigurationException; +use Symfony\Component\Routing\Matcher\RequestMatcherInterface; +use Symfony\Component\Routing\Matcher\UrlMatcherInterface; use Symfony\Component\Routing\RequestContext; class RouterListenerTest extends TestCase @@ -33,7 +37,7 @@ class RouterListenerTest extends TestCase protected function setUp(): void { - $this->requestStack = $this->getMockBuilder(RequestStack::class)->disableOriginalConstructor()->getMock(); + $this->requestStack = $this->createMock(RequestStack::class); } /** @@ -41,9 +45,8 @@ protected function setUp(): void */ public function testPort($defaultHttpPort, $defaultHttpsPort, $uri, $expectedHttpPort, $expectedHttpsPort) { - $urlMatcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\UrlMatcherInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $urlMatcher = $this->createMock(UrlMatcherInterface::class); + $context = new RequestContext(); $context->setHttpPort($defaultHttpPort); $context->setHttpsPort($defaultHttpsPort); @@ -72,7 +75,7 @@ public function getPortData() private function createRequestEventForUri(string $uri): RequestEvent { - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $request = Request::create($uri); $request->attributes->set('_controller', null); // Prevents going in to routing process @@ -87,11 +90,11 @@ public function testInvalidMatcher() public function testRequestMatcher() { - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $request = Request::create('http://localhost/'); $event = new RequestEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); - $requestMatcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\RequestMatcherInterface::class)->getMock(); + $requestMatcher = $this->createMock(RequestMatcherInterface::class); $requestMatcher->expects($this->once()) ->method('matchRequest') ->with($this->isInstanceOf(Request::class)) @@ -103,11 +106,11 @@ public function testRequestMatcher() public function testSubRequestWithDifferentMethod() { - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $request = Request::create('http://localhost/', 'post'); $event = new RequestEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); - $requestMatcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\RequestMatcherInterface::class)->getMock(); + $requestMatcher = $this->createMock(RequestMatcherInterface::class); $requestMatcher->expects($this->any()) ->method('matchRequest') ->with($this->isInstanceOf(Request::class)) @@ -119,7 +122,7 @@ public function testSubRequestWithDifferentMethod() $listener->onKernelRequest($event); // sub-request with another HTTP method - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $request = Request::create('http://localhost/', 'get'); $event = new RequestEvent($kernel, $request, HttpKernelInterface::SUB_REQUEST); @@ -133,17 +136,17 @@ public function testSubRequestWithDifferentMethod() */ public function testLoggingParameter($parameter, $log, $parameters) { - $requestMatcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\RequestMatcherInterface::class)->getMock(); + $requestMatcher = $this->createMock(RequestMatcherInterface::class); $requestMatcher->expects($this->once()) ->method('matchRequest') ->willReturn($parameter); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $logger->expects($this->once()) ->method('info') ->with($this->equalTo($log), $this->equalTo($parameters)); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $request = Request::create('http://localhost/'); $listener = new RouterListener($requestMatcher, $this->requestStack, new RequestContext(), $logger); @@ -162,7 +165,7 @@ public function testWithBadRequest() { $requestStack = new RequestStack(); - $requestMatcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\RequestMatcherInterface::class)->getMock(); + $requestMatcher = $this->createMock(RequestMatcherInterface::class); $requestMatcher->expects($this->never())->method('matchRequest'); $dispatcher = new EventDispatcher(); @@ -184,7 +187,7 @@ public function testNoRoutingConfigurationResponse() { $requestStack = new RequestStack(); - $requestMatcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\RequestMatcherInterface::class)->getMock(); + $requestMatcher = $this->createMock(RequestMatcherInterface::class); $requestMatcher ->expects($this->once()) ->method('matchRequest') @@ -204,12 +207,12 @@ public function testNoRoutingConfigurationResponse() public function testRequestWithBadHost() { - $this->expectException(\Symfony\Component\HttpKernel\Exception\BadRequestHttpException::class); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $this->expectException(BadRequestHttpException::class); + $kernel = $this->createMock(HttpKernelInterface::class); $request = Request::create('http://bad host %22/'); $event = new RequestEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); - $requestMatcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\RequestMatcherInterface::class)->getMock(); + $requestMatcher = $this->createMock(RequestMatcherInterface::class); $listener = new RouterListener($requestMatcher, $this->requestStack, new RequestContext()); $listener->onKernelRequest($event); diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/SaveSessionListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/SaveSessionListenerTest.php index 6cdd7476c9b7..f79b73c5fe47 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/SaveSessionListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/SaveSessionListenerTest.php @@ -27,7 +27,7 @@ class SaveSessionListenerTest extends TestCase public function testOnlyTriggeredOnMasterRequest() { $listener = new SaveSessionListener(); - $event = $this->getMockBuilder(ResponseEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(ResponseEvent::class); $event->expects($this->once())->method('isMasterRequest')->willReturn(false); $event->expects($this->never())->method('getRequest'); @@ -38,9 +38,9 @@ public function testOnlyTriggeredOnMasterRequest() public function testSessionSaved() { $listener = new SaveSessionListener(); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->disableOriginalConstructor()->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); - $session = $this->getMockBuilder(SessionInterface::class)->disableOriginalConstructor()->getMock(); + $session = $this->createMock(SessionInterface::class); $session->expects($this->once())->method('isStarted')->willReturn(true); $session->expects($this->once())->method('save'); diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/SessionListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/SessionListenerTest.php index 8131ff2ea110..de1069606b6b 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/SessionListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/SessionListenerTest.php @@ -32,7 +32,7 @@ class SessionListenerTest extends TestCase public function testOnlyTriggeredOnMasterRequest() { $listener = $this->getMockForAbstractClass(AbstractSessionListener::class); - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event->expects($this->once())->method('isMasterRequest')->willReturn(false); $event->expects($this->never())->method('getRequest'); @@ -42,12 +42,12 @@ public function testOnlyTriggeredOnMasterRequest() public function testSessionIsSet() { - $session = $this->getMockBuilder(Session::class)->disableOriginalConstructor()->getMock(); + $session = $this->createMock(Session::class); - $requestStack = $this->getMockBuilder(RequestStack::class)->getMock(); + $requestStack = $this->createMock(RequestStack::class); $requestStack->expects($this->once())->method('getMasterRequest')->willReturn(null); - $sessionStorage = $this->getMockBuilder(NativeSessionStorage::class)->getMock(); + $sessionStorage = $this->createMock(NativeSessionStorage::class); $sessionStorage->expects($this->never())->method('setOptions')->with(['cookie_secure' => true]); $container = new Container(); @@ -58,7 +58,7 @@ public function testSessionIsSet() $request = new Request(); $listener = new SessionListener($container); - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event->expects($this->once())->method('isMasterRequest')->willReturn(true); $event->expects($this->once())->method('getRequest')->willReturn($request); @@ -70,14 +70,14 @@ public function testSessionIsSet() public function testResponseIsPrivateIfSessionStarted() { - $session = $this->getMockBuilder(Session::class)->disableOriginalConstructor()->getMock(); + $session = $this->createMock(Session::class); $session->expects($this->exactly(2))->method('getUsageIndex')->will($this->onConsecutiveCalls(0, 1)); $container = new Container(); $container->set('initialized_session', $session); $listener = new SessionListener($container); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->disableOriginalConstructor()->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $request = new Request(); $listener->onKernelRequest(new RequestEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST)); @@ -95,14 +95,14 @@ public function testResponseIsPrivateIfSessionStarted() public function testResponseIsStillPublicIfSessionStartedAndHeaderPresent() { - $session = $this->getMockBuilder(Session::class)->disableOriginalConstructor()->getMock(); + $session = $this->createMock(Session::class); $session->expects($this->exactly(2))->method('getUsageIndex')->will($this->onConsecutiveCalls(0, 1)); $container = new Container(); $container->set('initialized_session', $session); $listener = new SessionListener($container); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->disableOriginalConstructor()->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $request = new Request(); $listener->onKernelRequest(new RequestEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST)); @@ -122,7 +122,7 @@ public function testResponseIsStillPublicIfSessionStartedAndHeaderPresent() public function testUninitializedSession() { - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->disableOriginalConstructor()->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $response = new Response(); $response->setSharedMaxAge(60); $response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true'); @@ -143,7 +143,7 @@ public function testUninitializedSession() public function testSurrogateMasterRequestIsPublic() { - $session = $this->getMockBuilder(Session::class)->disableOriginalConstructor()->getMock(); + $session = $this->createMock(Session::class); $session->expects($this->exactly(4))->method('getUsageIndex')->will($this->onConsecutiveCalls(0, 1, 1, 1)); $container = new Container(); @@ -151,7 +151,7 @@ public function testSurrogateMasterRequestIsPublic() $container->set('session', $session); $listener = new SessionListener($container); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->disableOriginalConstructor()->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $request = new Request(); $response = new Response(); @@ -182,9 +182,9 @@ public function testSurrogateMasterRequestIsPublic() public function testGetSessionIsCalledOnce() { - $session = $this->getMockBuilder(Session::class)->disableOriginalConstructor()->getMock(); - $sessionStorage = $this->getMockBuilder(NativeSessionStorage::class)->getMock(); - $kernel = $this->getMockBuilder(KernelInterface::class)->getMock(); + $session = $this->createMock(Session::class); + $sessionStorage = $this->createMock(NativeSessionStorage::class); + $kernel = $this->createMock(KernelInterface::class); $sessionStorage->expects($this->once()) ->method('setOptions') diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/SurrogateListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/SurrogateListenerTest.php index e4b8b2d558ee..fc7e4d83ac4f 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/SurrogateListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/SurrogateListenerTest.php @@ -26,7 +26,7 @@ class SurrogateListenerTest extends TestCase public function testFilterDoesNothingForSubRequests() { $dispatcher = new EventDispatcher(); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $response = new Response('foo '); $listener = new SurrogateListener(new Esi()); @@ -40,7 +40,7 @@ public function testFilterDoesNothingForSubRequests() public function testFilterWhenThereIsSomeEsiIncludes() { $dispatcher = new EventDispatcher(); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $response = new Response('foo '); $listener = new SurrogateListener(new Esi()); @@ -54,7 +54,7 @@ public function testFilterWhenThereIsSomeEsiIncludes() public function testFilterWhenThereIsNoEsiIncludes() { $dispatcher = new EventDispatcher(); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $response = new Response('foo'); $listener = new SurrogateListener(new Esi()); diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/TestSessionListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/TestSessionListenerTest.php index e0a5cc69da80..2ec6581694c8 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/TestSessionListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/TestSessionListenerTest.php @@ -14,9 +14,11 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\EventListener\AbstractTestSessionListener; use Symfony\Component\HttpKernel\EventListener\SessionListener; use Symfony\Component\HttpKernel\EventListener\TestSessionListener; use Symfony\Component\HttpKernel\HttpKernelInterface; @@ -42,7 +44,7 @@ class TestSessionListenerTest extends TestCase protected function setUp(): void { - $this->listener = $this->getMockForAbstractClass(\Symfony\Component\HttpKernel\EventListener\AbstractTestSessionListener::class); + $this->listener = $this->getMockForAbstractClass(AbstractTestSessionListener::class); $this->session = $this->getSession(); $this->listener->expects($this->any()) ->method('getSession') @@ -95,7 +97,7 @@ public function testEmptySessionWithNewSessionIdDoesSendCookie() $this->sessionIsEmpty(); $this->fixSessionId('456'); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $request = Request::create('/', 'GET', [], ['MOCKSESSID' => '123']); $event = new RequestEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); $this->listener->onKernelRequest($event); @@ -114,7 +116,7 @@ public function testSessionWithNewSessionIdAndNewCookieDoesNotSendAnotherCookie( $this->sessionIsEmpty(); $this->fixSessionId('456'); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $request = Request::create('/', 'GET', [], ['MOCKSESSID' => '123']); $event = new RequestEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); $this->listener->onKernelRequest($event); @@ -145,7 +147,7 @@ public function testUnstartedSessionIsNotSave() public function testDoesNotThrowIfRequestDoesNotHaveASession() { - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $event = new ResponseEvent($kernel, new Request(), HttpKernelInterface::MASTER_REQUEST, new Response()); $this->listener->onKernelResponse($event); @@ -157,7 +159,7 @@ private function filterResponse(Request $request, $type = HttpKernelInterface::M { $request->setSession($this->session); $response = $response ?: new Response(); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $event = new ResponseEvent($kernel, $request, $type, $response); $this->listener->onKernelResponse($event); @@ -209,11 +211,7 @@ private function fixSessionId($sessionId) private function getSession() { - $mock = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\Session::class) - ->disableOriginalConstructor() - ->getMock(); - - // set return value for getName() + $mock = $this->createMock(Session::class); $mock->expects($this->any())->method('getName')->willReturn('MOCKSESSID'); return $mock; diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/TranslatorListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/TranslatorListenerTest.php index 1fe4d1f2fafa..26097696dd57 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/TranslatorListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/TranslatorListenerTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpKernel\Event\FinishRequestEvent; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\EventListener\TranslatorListener; @@ -30,8 +31,8 @@ class TranslatorListenerTest extends TestCase protected function setUp(): void { - $this->translator = $this->getMockBuilder(LocaleAwareInterface::class)->getMock(); - $this->requestStack = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestStack::class)->getMock(); + $this->translator = $this->createMock(LocaleAwareInterface::class); + $this->requestStack = $this->createMock(RequestStack::class); $this->listener = new TranslatorListener($this->translator, $this->requestStack); } @@ -105,7 +106,7 @@ public function testDefaultLocaleIsUsedOnExceptionsInOnKernelFinishRequest() private function createHttpKernel() { - return $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + return $this->createMock(HttpKernelInterface::class); } private function createRequest($locale) diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/ValidateRequestListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/ValidateRequestListenerTest.php index 96b686d91bea..d23832d80a7a 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/ValidateRequestListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/ValidateRequestListenerTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\EventListener\ValidateRequestListener; @@ -28,9 +29,9 @@ protected function tearDown(): void public function testListenerThrowsWhenMasterRequestHasInconsistentClientIps() { - $this->expectException(\Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException::class); + $this->expectException(ConflictingHeadersException::class); $dispatcher = new EventDispatcher(); - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $request = new Request(); $request->setTrustedProxies(['1.1.1.1'], Request::HEADER_X_FORWARDED_FOR | Request::HEADER_FORWARDED); diff --git a/src/Symfony/Component/HttpKernel/Tests/Fragment/EsiFragmentRendererTest.php b/src/Symfony/Component/HttpKernel/Tests/Fragment/EsiFragmentRendererTest.php index c9af77149c25..3817f4897efb 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Fragment/EsiFragmentRendererTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Fragment/EsiFragmentRendererTest.php @@ -15,6 +15,7 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Controller\ControllerReference; use Symfony\Component\HttpKernel\Fragment\EsiFragmentRenderer; +use Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer; use Symfony\Component\HttpKernel\HttpCache\Esi; use Symfony\Component\HttpKernel\UriSigner; @@ -91,7 +92,7 @@ public function testRenderAltControllerReferenceWithoutSignerThrowsException() private function getInlineStrategy($called = false) { - $inline = $this->getMockBuilder(\Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer::class)->disableOriginalConstructor()->getMock(); + $inline = $this->createMock(InlineFragmentRenderer::class); if ($called) { $inline->expects($this->once())->method('render'); diff --git a/src/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.php b/src/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.php index fa011c8f29cc..7ad4f3e704a5 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.php @@ -13,8 +13,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Fragment\FragmentHandler; +use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface; /** * @group time-sensitive @@ -25,10 +27,7 @@ class FragmentHandlerTest extends TestCase protected function setUp(): void { - $this->requestStack = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestStack::class) - ->disableOriginalConstructor() - ->getMock() - ; + $this->requestStack = $this->createMock(RequestStack::class); $this->requestStack ->expects($this->any()) ->method('getCurrentRequest') @@ -69,7 +68,7 @@ public function testRender() protected function getHandler($returnValue, $arguments = []) { - $renderer = $this->getMockBuilder(\Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface::class)->getMock(); + $renderer = $this->createMock(FragmentRendererInterface::class); $renderer ->expects($this->any()) ->method('getName') diff --git a/src/Symfony/Component/HttpKernel/Tests/Fragment/HIncludeFragmentRendererTest.php b/src/Symfony/Component/HttpKernel/Tests/Fragment/HIncludeFragmentRendererTest.php index ae1cb155162f..665c1d458a53 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Fragment/HIncludeFragmentRendererTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Fragment/HIncludeFragmentRendererTest.php @@ -16,6 +16,7 @@ use Symfony\Component\HttpKernel\Controller\ControllerReference; use Symfony\Component\HttpKernel\Fragment\HIncludeFragmentRenderer; use Symfony\Component\HttpKernel\UriSigner; +use Symfony\Component\Templating\EngineInterface; use Twig\Environment; use Twig\Loader\ArrayLoader; @@ -86,7 +87,7 @@ public function testRenderWithTwigAndDefaultText() */ public function testRenderWithDefaultTextLegacy() { - $engine = $this->getMockBuilder(\Symfony\Component\Templating\EngineInterface::class)->getMock(); + $engine = $this->createMock(EngineInterface::class); $engine->expects($this->once()) ->method('exists') ->with('default') diff --git a/src/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php b/src/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php index c25297dbe4da..c70a1ae6f015 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php @@ -16,10 +16,13 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface; use Symfony\Component\HttpKernel\Controller\ControllerReference; +use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer; use Symfony\Component\HttpKernel\HttpKernel; +use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; @@ -72,7 +75,7 @@ public function testRenderWithTrustedHeaderDisabled() public function testRenderExceptionNoIgnoreErrors() { $this->expectException(\RuntimeException::class); - $dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); + $dispatcher = $this->createMock(EventDispatcherInterface::class); $dispatcher->expects($this->never())->method('dispatch'); $strategy = new InlineFragmentRenderer($this->getKernel($this->throwException(new \RuntimeException('foo'))), $dispatcher); @@ -86,7 +89,7 @@ public function testRenderExceptionIgnoreErrors() $kernel = $this->getKernel($this->throwException($exception)); $request = Request::create('/'); $expectedEvent = new ExceptionEvent($kernel, $request, $kernel::SUB_REQUEST, $exception); - $dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); + $dispatcher = $this->createMock(EventDispatcherInterface::class); $dispatcher->expects($this->once())->method('dispatch')->with($expectedEvent, KernelEvents::EXCEPTION); $strategy = new InlineFragmentRenderer($kernel, $dispatcher); @@ -106,7 +109,7 @@ public function testRenderExceptionIgnoreErrorsWithAlt() private function getKernel($returnValue) { - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $kernel ->expects($this->any()) ->method('handle') @@ -118,7 +121,7 @@ private function getKernel($returnValue) public function testExceptionInSubRequestsDoesNotMangleOutputBuffers() { - $controllerResolver = $this->getMockBuilder(\Symfony\Component\HttpKernel\Controller\ControllerResolverInterface::class)->getMock(); + $controllerResolver = $this->createMock(ControllerResolverInterface::class); $controllerResolver ->expects($this->once()) ->method('getController') @@ -129,7 +132,7 @@ public function testExceptionInSubRequestsDoesNotMangleOutputBuffers() }) ; - $argumentResolver = $this->getMockBuilder(\Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface::class)->getMock(); + $argumentResolver = $this->createMock(ArgumentResolverInterface::class); $argumentResolver ->expects($this->once()) ->method('getArguments') @@ -258,7 +261,7 @@ public function testIpAddressOfRangedTrustedProxyIsSetAsRemote() */ private function getKernelExpectingRequest(Request $request, $strict = false) { - $kernel = $this->getMockBuilder(\Symfony\Component\HttpKernel\HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $kernel ->expects($this->once()) ->method('handle') diff --git a/src/Symfony/Component/HttpKernel/Tests/Fragment/RoutableFragmentRendererTest.php b/src/Symfony/Component/HttpKernel/Tests/Fragment/RoutableFragmentRendererTest.php index 5980284afe45..d17643c18675 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Fragment/RoutableFragmentRendererTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Fragment/RoutableFragmentRendererTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Controller\ControllerReference; +use Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer; class RoutableFragmentRendererTest extends TestCase { @@ -74,7 +75,7 @@ public function getGenerateFragmentUriDataWithNonScalar() private function callGenerateFragmentUriMethod(ControllerReference $reference, Request $request, $absolute = false) { - $renderer = $this->getMockForAbstractClass(\Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer::class); + $renderer = $this->getMockForAbstractClass(RoutableFragmentRenderer::class); $r = new \ReflectionObject($renderer); $m = $r->getMethod('generateFragmentUri'); $m->setAccessible(true); diff --git a/src/Symfony/Component/HttpKernel/Tests/Fragment/SsiFragmentRendererTest.php b/src/Symfony/Component/HttpKernel/Tests/Fragment/SsiFragmentRendererTest.php index db203f91de9b..63a92028f423 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Fragment/SsiFragmentRendererTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Fragment/SsiFragmentRendererTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Controller\ControllerReference; +use Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer; use Symfony\Component\HttpKernel\Fragment\SsiFragmentRenderer; use Symfony\Component\HttpKernel\HttpCache\Ssi; use Symfony\Component\HttpKernel\UriSigner; @@ -82,7 +83,7 @@ public function testRenderAltControllerReferenceWithoutSignerThrowsException() private function getInlineStrategy($called = false) { - $inline = $this->getMockBuilder(\Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer::class)->disableOriginalConstructor()->getMock(); + $inline = $this->createMock(InlineFragmentRenderer::class); if ($called) { $inline->expects($this->once())->method('render'); diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php index 5246721a645d..e708c2ae5f4a 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php @@ -15,6 +15,7 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpCache\Esi; +use Symfony\Component\HttpKernel\HttpCache\HttpCache; class EsiTest extends TestCase { @@ -222,7 +223,7 @@ public function testHandleWhenResponseIsNot200AndAltIsPresent() protected function getCache($request, $response) { - $cache = $this->getMockBuilder(\Symfony\Component\HttpKernel\HttpCache\HttpCache::class)->setMethods(['getRequest', 'handle'])->disableOriginalConstructor()->getMock(); + $cache = $this->getMockBuilder(HttpCache::class)->setMethods(['getRequest', 'handle'])->disableOriginalConstructor()->getMock(); $cache->expects($this->any()) ->method('getRequest') ->willReturn($request) diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php index 932f46c6efd8..d9dd572bf1a6 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php @@ -16,7 +16,9 @@ use Symfony\Component\HttpKernel\HttpCache\Esi; use Symfony\Component\HttpKernel\HttpCache\HttpCache; use Symfony\Component\HttpKernel\HttpCache\Store; +use Symfony\Component\HttpKernel\HttpCache\StoreInterface; use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\HttpKernel\Kernel; /** * @group time-sensitive @@ -25,7 +27,7 @@ class HttpCacheTest extends HttpCacheTestCase { public function testTerminateDelegatesTerminationOnlyForTerminableInterface() { - $storeMock = $this->getMockBuilder(\Symfony\Component\HttpKernel\HttpCache\StoreInterface::class) + $storeMock = $this->getMockBuilder(StoreInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -37,7 +39,7 @@ public function testTerminateDelegatesTerminationOnlyForTerminableInterface() $this->assertFalse($kernel->terminateCalled, 'terminate() is never called if the kernel class does not implement TerminableInterface'); // implements TerminableInterface - $kernelMock = $this->getMockBuilder(\Symfony\Component\HttpKernel\Kernel::class) + $kernelMock = $this->getMockBuilder(Kernel::class) ->disableOriginalConstructor() ->setMethods(['terminate', 'registerBundles', 'registerContainerConfiguration']) ->getMock(); @@ -1488,8 +1490,8 @@ public function testDoesNotCacheOptionsRequest() public function testUsesOriginalRequestForSurrogate() { - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); - $store = $this->getMockBuilder(\Symfony\Component\HttpKernel\HttpCache\StoreInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); + $store = $this->createMock(StoreInterface::class); $kernel ->expects($this->exactly(2)) diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpCache/SsiTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpCache/SsiTest.php index 23c7410a280b..157c4d7455b5 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpCache/SsiTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpCache/SsiTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\HttpCache\HttpCache; use Symfony\Component\HttpKernel\HttpCache\Ssi; class SsiTest extends TestCase @@ -189,7 +190,7 @@ public function testHandleWhenResponseIsNot200AndAltIsPresent() protected function getCache($request, $response) { - $cache = $this->getMockBuilder(\Symfony\Component\HttpKernel\HttpCache\HttpCache::class)->setMethods(['getRequest', 'handle'])->disableOriginalConstructor()->getMock(); + $cache = $this->getMockBuilder(HttpCache::class)->setMethods(['getRequest', 'handle'])->disableOriginalConstructor()->getMock(); $cache->expects($this->any()) ->method('getRequest') ->willReturn($request) diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpClientKernelTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpClientKernelTest.php index 2b904bf9a2ca..27b3a82e039a 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpClientKernelTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpClientKernelTest.php @@ -24,10 +24,10 @@ public function testHandlePassesMaxRedirectsHttpClientOption() $request = new Request(); $request->attributes->set('http_client_options', ['max_redirects' => 50]); - $response = $this->getMockBuilder(ResponseInterface::class)->getMock(); + $response = $this->createMock(ResponseInterface::class); $response->expects($this->once())->method('getStatusCode')->willReturn(200); - $client = $this->getMockBuilder(HttpClientInterface::class)->getMock(); + $client = $this->createMock(HttpClientInterface::class); $client ->expects($this->once()) ->method('request') diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpKernelBrowserTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpKernelBrowserTest.php index eab6c5221c12..7cd4d52d3965 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpKernelBrowserTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpKernelBrowserTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\HttpKernel\HttpKernelBrowser; @@ -31,7 +32,7 @@ public function testDoRequest() $client->request('GET', '/'); $this->assertEquals('Request: /', $client->getResponse()->getContent(), '->doRequest() uses the request handler to make the request'); $this->assertInstanceOf(\Symfony\Component\BrowserKit\Request::class, $client->getInternalRequest()); - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\Request::class, $client->getRequest()); + $this->assertInstanceOf(Request::class, $client->getRequest()); $this->assertInstanceOf(\Symfony\Component\BrowserKit\Response::class, $client->getInternalResponse()); $this->assertInstanceOf(Response::class, $client->getResponse()); diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php index 5c954261b61b..014dc752c32a 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php @@ -21,8 +21,10 @@ use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface; use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; +use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\ControllerDoesNotReturnResponseException; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\HttpKernel; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\KernelEvents; @@ -156,7 +158,7 @@ public function testHandleWhenAListenerReturnsAResponse() public function testHandleWhenNoControllerIsFound() { - $this->expectException(\Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class); + $this->expectException(NotFoundHttpException::class); $dispatcher = new EventDispatcher(); $kernel = $this->getHttpKernel($dispatcher, false); @@ -315,7 +317,7 @@ public function testVerifyRequestStackPushPopDuringHandle() public function testInconsistentClientIpsOnMasterRequests() { - $this->expectException(\Symfony\Component\HttpKernel\Exception\BadRequestHttpException::class); + $this->expectException(BadRequestHttpException::class); $request = new Request(); $request->setTrustedProxies(['1.1.1.1'], Request::HEADER_X_FORWARDED_FOR | Request::HEADER_FORWARDED); $request->server->set('REMOTE_ADDR', '1.1.1.1'); @@ -339,13 +341,13 @@ private function getHttpKernel(EventDispatcherInterface $eventDispatcher, $contr $controller = function () { return new Response('Hello'); }; } - $controllerResolver = $this->getMockBuilder(ControllerResolverInterface::class)->getMock(); + $controllerResolver = $this->createMock(ControllerResolverInterface::class); $controllerResolver ->expects($this->any()) ->method('getController') ->willReturn($controller); - $argumentResolver = $this->getMockBuilder(ArgumentResolverInterface::class)->getMock(); + $argumentResolver = $this->createMock(ArgumentResolverInterface::class); $argumentResolver ->expects($this->any()) ->method('getArguments') diff --git a/src/Symfony/Component/HttpKernel/Tests/KernelTest.php b/src/Symfony/Component/HttpKernel/Tests/KernelTest.php index 570e6f029893..9e48e4274e40 100644 --- a/src/Symfony/Component/HttpKernel/Tests/KernelTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/KernelTest.php @@ -19,9 +19,11 @@ use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\HttpKernel\Bundle\BundleInterface; use Symfony\Component\HttpKernel\DependencyInjection\ResettableServicePass; use Symfony\Component\HttpKernel\DependencyInjection\ServicesResetter; +use Symfony\Component\HttpKernel\HttpKernel; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\HttpKernel\Tests\Fixtures\KernelForOverrideName; @@ -125,7 +127,7 @@ public function testBootInitializesBundlesAndContainer() public function testBootSetsTheContainerToTheBundles() { - $bundle = $this->getMockBuilder(\Symfony\Component\HttpKernel\Bundle\Bundle::class)->getMock(); + $bundle = $this->createMock(Bundle::class); $bundle->expects($this->once()) ->method('setContainer'); @@ -167,7 +169,7 @@ public function testBootKernelSeveralTimesOnlyInitializesBundlesOnce() public function testShutdownCallsShutdownOnAllBundles() { - $bundle = $this->getMockBuilder(\Symfony\Component\HttpKernel\Bundle\Bundle::class)->getMock(); + $bundle = $this->createMock(Bundle::class); $bundle->expects($this->once()) ->method('shutdown'); @@ -179,7 +181,7 @@ public function testShutdownCallsShutdownOnAllBundles() public function testShutdownGivesNullContainerToAllBundles() { - $bundle = $this->getMockBuilder(\Symfony\Component\HttpKernel\Bundle\Bundle::class)->getMock(); + $bundle = $this->createMock(Bundle::class); $bundle->expects($this->exactly(2)) ->method('setContainer') ->withConsecutive( @@ -202,7 +204,7 @@ public function testHandleCallsHandleOnHttpKernel() $catch = true; $request = new Request(); - $httpKernelMock = $this->getMockBuilder(\Symfony\Component\HttpKernel\HttpKernel::class) + $httpKernelMock = $this->getMockBuilder(HttpKernel::class) ->disableOriginalConstructor() ->getMock(); $httpKernelMock @@ -224,7 +226,7 @@ public function testHandleBootsTheKernel() $catch = true; $request = new Request(); - $httpKernelMock = $this->getMockBuilder(\Symfony\Component\HttpKernel\HttpKernel::class) + $httpKernelMock = $this->getMockBuilder(HttpKernel::class) ->disableOriginalConstructor() ->getMock(); @@ -547,7 +549,7 @@ public function testTerminateDelegatesTerminationOnlyForTerminableInterface() $this->assertFalse($httpKernel->terminateCalled, 'terminate() is never called if the kernel class does not implement TerminableInterface'); // implements TerminableInterface - $httpKernelMock = $this->getMockBuilder(\Symfony\Component\HttpKernel\HttpKernel::class) + $httpKernelMock = $this->getMockBuilder(HttpKernel::class) ->disableOriginalConstructor() ->setMethods(['terminate']) ->getMock(); diff --git a/src/Symfony/Component/Intl/Tests/Collator/CollatorTest.php b/src/Symfony/Component/Intl/Tests/Collator/CollatorTest.php index 9b55057818de..d73263e15191 100644 --- a/src/Symfony/Component/Intl/Tests/Collator/CollatorTest.php +++ b/src/Symfony/Component/Intl/Tests/Collator/CollatorTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Intl\Tests\Collator; use Symfony\Component\Intl\Collator\Collator; +use Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException; use Symfony\Component\Intl\Exception\MethodNotImplementedException; use Symfony\Component\Intl\Globals\IntlGlobals; @@ -19,7 +20,7 @@ class CollatorTest extends AbstractCollatorTest { public function testConstructorWithUnsupportedLocale() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException::class); + $this->expectException(MethodArgumentValueNotImplementedException::class); $this->getCollator('pt_BR'); } diff --git a/src/Symfony/Component/Intl/Tests/CurrenciesTest.php b/src/Symfony/Component/Intl/Tests/CurrenciesTest.php index 58fc8fcb7241..f69d43b1c663 100644 --- a/src/Symfony/Component/Intl/Tests/CurrenciesTest.php +++ b/src/Symfony/Component/Intl/Tests/CurrenciesTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Intl\Tests; use Symfony\Component\Intl\Currencies; +use Symfony\Component\Intl\Exception\MissingResourceException; /** * @group intl-data @@ -725,7 +726,7 @@ function ($value) { return [$value]; }, */ public function testGetNumericCodeFailsIfNoNumericEquivalent($currency) { - $this->expectException(\Symfony\Component\Intl\Exception\MissingResourceException::class); + $this->expectException(MissingResourceException::class); Currencies::getNumericCode($currency); } @@ -770,13 +771,13 @@ function ($value) { return [$value]; }, */ public function testForNumericCodeFailsIfInvalidNumericCode($currency) { - $this->expectException(\Symfony\Component\Intl\Exception\MissingResourceException::class); + $this->expectException(MissingResourceException::class); Currencies::forNumericCode($currency); } public function testGetNameWithInvalidCurrencyCode() { - $this->expectException(\Symfony\Component\Intl\Exception\MissingResourceException::class); + $this->expectException(MissingResourceException::class); Currencies::getName('foo'); } diff --git a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/BundleEntryReaderTest.php b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/BundleEntryReaderTest.php index cf1239bf4f66..ee23742c7be7 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/BundleEntryReaderTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/BundleEntryReaderTest.php @@ -14,6 +14,8 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\Intl\Data\Bundle\Reader\BundleEntryReader; +use Symfony\Component\Intl\Data\Bundle\Reader\BundleEntryReaderInterface; +use Symfony\Component\Intl\Exception\MissingResourceException; use Symfony\Component\Intl\Exception\ResourceBundleNotFoundException; /** @@ -64,7 +66,7 @@ class BundleEntryReaderTest extends TestCase protected function setUp(): void { - $this->readerImpl = $this->getMockBuilder(\Symfony\Component\Intl\Data\Bundle\Reader\BundleEntryReaderInterface::class)->getMock(); + $this->readerImpl = $this->createMock(BundleEntryReaderInterface::class); $this->reader = new BundleEntryReader($this->readerImpl); } @@ -103,7 +105,7 @@ public function testReadExistingEntry() public function testReadNonExistingEntry() { - $this->expectException(\Symfony\Component\Intl\Exception\MissingResourceException::class); + $this->expectException(MissingResourceException::class); $this->readerImpl->expects($this->once()) ->method('read') ->with(self::RES_DIR, 'root') @@ -127,7 +129,7 @@ public function testFallbackIfEntryDoesNotExist() public function testDontFallbackIfEntryDoesNotExistAndFallbackDisabled() { - $this->expectException(\Symfony\Component\Intl\Exception\MissingResourceException::class); + $this->expectException(MissingResourceException::class); $this->readerImpl->expects($this->once()) ->method('read') ->with(self::RES_DIR, 'en_GB') @@ -154,7 +156,7 @@ public function testFallbackIfLocaleDoesNotExist() public function testDontFallbackIfLocaleDoesNotExistAndFallbackDisabled() { - $this->expectException(\Symfony\Component\Intl\Exception\MissingResourceException::class); + $this->expectException(MissingResourceException::class); $this->readerImpl->expects($this->once()) ->method('read') ->with(self::RES_DIR, 'en_GB') @@ -279,7 +281,7 @@ public function testMergeExistingEntryWithNonExistingFallbackEntry($childData, $ public function testFailIfEntryFoundNeitherInParentNorChild() { - $this->expectException(\Symfony\Component\Intl\Exception\MissingResourceException::class); + $this->expectException(MissingResourceException::class); $this->readerImpl ->method('read') ->withConsecutive( diff --git a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/IntlBundleReaderTest.php b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/IntlBundleReaderTest.php index 2f04e6802427..2861c91bc871 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/IntlBundleReaderTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/IntlBundleReaderTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Intl\Data\Bundle\Reader\IntlBundleReader; +use Symfony\Component\Intl\Exception\ResourceBundleNotFoundException; +use Symfony\Component\Intl\Exception\RuntimeException; /** * @author Bernhard Schussek @@ -75,19 +77,19 @@ public function testReadDoesNotFollowFallbackAlias() public function testReadFailsIfNonExistingLocale() { - $this->expectException(\Symfony\Component\Intl\Exception\ResourceBundleNotFoundException::class); + $this->expectException(ResourceBundleNotFoundException::class); $this->reader->read(__DIR__.'/Fixtures/res', 'foo'); } public function testReadFailsIfNonExistingFallbackLocale() { - $this->expectException(\Symfony\Component\Intl\Exception\ResourceBundleNotFoundException::class); + $this->expectException(ResourceBundleNotFoundException::class); $this->reader->read(__DIR__.'/Fixtures/res', 'ro_AT'); } public function testReadFailsIfNonExistingDirectory() { - $this->expectException(\Symfony\Component\Intl\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->reader->read(__DIR__.'/foo', 'ro'); } } diff --git a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/JsonBundleReaderTest.php b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/JsonBundleReaderTest.php index 3fdef2b664e9..f6abfc469342 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/JsonBundleReaderTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/JsonBundleReaderTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Intl\Data\Bundle\Reader\JsonBundleReader; +use Symfony\Component\Intl\Exception\ResourceBundleNotFoundException; +use Symfony\Component\Intl\Exception\RuntimeException; /** * @author Bernhard Schussek @@ -40,31 +42,31 @@ public function testReadReturnsArray() public function testReadFailsIfNonExistingLocale() { - $this->expectException(\Symfony\Component\Intl\Exception\ResourceBundleNotFoundException::class); + $this->expectException(ResourceBundleNotFoundException::class); $this->reader->read(__DIR__.'/Fixtures/json', 'foo'); } public function testReadFailsIfNonExistingDirectory() { - $this->expectException(\Symfony\Component\Intl\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->reader->read(__DIR__.'/foo', 'en'); } public function testReadFailsIfNotAFile() { - $this->expectException(\Symfony\Component\Intl\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->reader->read(__DIR__.'/Fixtures/NotAFile', 'en'); } public function testReadFailsIfInvalidJson() { - $this->expectException(\Symfony\Component\Intl\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->reader->read(__DIR__.'/Fixtures/json', 'en_Invalid'); } public function testReaderDoesNotBreakOutOfGivenPath() { - $this->expectException(\Symfony\Component\Intl\Exception\ResourceBundleNotFoundException::class); + $this->expectException(ResourceBundleNotFoundException::class); $this->reader->read(__DIR__.'/Fixtures/json', '../invalid_directory/en'); } } diff --git a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/PhpBundleReaderTest.php b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/PhpBundleReaderTest.php index f4e020f0751b..fcb2480123af 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/PhpBundleReaderTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/PhpBundleReaderTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Intl\Data\Bundle\Reader\PhpBundleReader; +use Symfony\Component\Intl\Exception\ResourceBundleNotFoundException; +use Symfony\Component\Intl\Exception\RuntimeException; /** * @author Bernhard Schussek @@ -40,25 +42,25 @@ public function testReadReturnsArray() public function testReadFailsIfNonExistingLocale() { - $this->expectException(\Symfony\Component\Intl\Exception\ResourceBundleNotFoundException::class); + $this->expectException(ResourceBundleNotFoundException::class); $this->reader->read(__DIR__.'/Fixtures/php', 'foo'); } public function testReadFailsIfNonExistingDirectory() { - $this->expectException(\Symfony\Component\Intl\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->reader->read(__DIR__.'/foo', 'en'); } public function testReadFailsIfNotAFile() { - $this->expectException(\Symfony\Component\Intl\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->reader->read(__DIR__.'/Fixtures/NotAFile', 'en'); } public function testReaderDoesNotBreakOutOfGivenPath() { - $this->expectException(\Symfony\Component\Intl\Exception\ResourceBundleNotFoundException::class); + $this->expectException(ResourceBundleNotFoundException::class); $this->reader->read(__DIR__.'/Fixtures/php', '../invalid_directory/en'); } } diff --git a/src/Symfony/Component/Intl/Tests/Data/Provider/AbstractCurrencyDataProviderTest.php b/src/Symfony/Component/Intl/Tests/Data/Provider/AbstractCurrencyDataProviderTest.php index 2cd798b0955a..24cf48d06874 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Provider/AbstractCurrencyDataProviderTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Provider/AbstractCurrencyDataProviderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Intl\Tests\Data\Provider; use Symfony\Component\Intl\Data\Provider\CurrencyDataProvider; +use Symfony\Component\Intl\Exception\MissingResourceException; use Symfony\Component\Intl\Intl; /** @@ -758,7 +759,7 @@ function ($value) { return [$value]; }, */ public function testGetNumericCodeFailsIfNoNumericEquivalent($currency) { - $this->expectException(\Symfony\Component\Intl\Exception\MissingResourceException::class); + $this->expectException(MissingResourceException::class); $this->dataProvider->getNumericCode($currency); } @@ -803,7 +804,7 @@ function ($value) { return [$value]; }, */ public function testForNumericCodeFailsIfInvalidNumericCode($currency) { - $this->expectException(\Symfony\Component\Intl\Exception\MissingResourceException::class); + $this->expectException(MissingResourceException::class); $this->dataProvider->forNumericCode($currency); } diff --git a/src/Symfony/Component/Intl/Tests/Data/Provider/AbstractLanguageDataProviderTest.php b/src/Symfony/Component/Intl/Tests/Data/Provider/AbstractLanguageDataProviderTest.php index faf2b0bfea99..914f3ddc2a89 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Provider/AbstractLanguageDataProviderTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Provider/AbstractLanguageDataProviderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Intl\Tests\Data\Provider; use Symfony\Component\Intl\Data\Provider\LanguageDataProvider; +use Symfony\Component\Intl\Exception\MissingResourceException; use Symfony\Component\Intl\Intl; /** @@ -924,7 +925,7 @@ function ($value) { return [$value]; }, */ public function testGetAlpha3CodeFailsIfNoAlpha3Equivalent($currency) { - $this->expectException(\Symfony\Component\Intl\Exception\MissingResourceException::class); + $this->expectException(MissingResourceException::class); $this->dataProvider->getAlpha3Code($currency); } } diff --git a/src/Symfony/Component/Intl/Tests/Data/Util/RingBufferTest.php b/src/Symfony/Component/Intl/Tests/Data/Util/RingBufferTest.php index 3709ce17cdd7..cd21b8f9b0ed 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Util/RingBufferTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Util/RingBufferTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Intl\Data\Util\RingBuffer; +use Symfony\Component\Intl\Exception\OutOfBoundsException; /** * @author Bernhard Schussek @@ -54,7 +55,7 @@ public function testWritePastBuffer() public function testReadNonExistingFails() { - $this->expectException(\Symfony\Component\Intl\Exception\OutOfBoundsException::class); + $this->expectException(OutOfBoundsException::class); $this->buffer['foo']; } @@ -72,7 +73,7 @@ public function testUnsetNonExistingSucceeds() public function testReadOverwrittenFails() { - $this->expectException(\Symfony\Component\Intl\Exception\OutOfBoundsException::class); + $this->expectException(OutOfBoundsException::class); $this->buffer[0] = 'foo'; $this->buffer['bar'] = 'baz'; $this->buffer[2] = 'bam'; diff --git a/src/Symfony/Component/Intl/Tests/DateFormatter/IntlDateFormatterTest.php b/src/Symfony/Component/Intl/Tests/DateFormatter/IntlDateFormatterTest.php index db61df14b9a3..de61e7fb8409 100644 --- a/src/Symfony/Component/Intl/Tests/DateFormatter/IntlDateFormatterTest.php +++ b/src/Symfony/Component/Intl/Tests/DateFormatter/IntlDateFormatterTest.php @@ -12,6 +12,10 @@ namespace Symfony\Component\Intl\Tests\DateFormatter; use Symfony\Component\Intl\DateFormatter\IntlDateFormatter; +use Symfony\Component\Intl\Exception\MethodArgumentNotImplementedException; +use Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException; +use Symfony\Component\Intl\Exception\MethodNotImplementedException; +use Symfony\Component\Intl\Exception\NotImplementedException; use Symfony\Component\Intl\Globals\IntlGlobals; class IntlDateFormatterTest extends AbstractIntlDateFormatterTest @@ -36,7 +40,7 @@ public function testConstructorWithoutCalendar() public function testConstructorWithUnsupportedLocale() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException::class); + $this->expectException(MethodArgumentValueNotImplementedException::class); $this->getDateFormatter('pt_BR', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT); } @@ -66,7 +70,7 @@ public function testFormatWithUnsupportedTimestampArgument() try { $formatter->format($localtime); } catch (\Exception $e) { - $this->assertInstanceOf(\Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException::class, $e); + $this->assertInstanceOf(MethodArgumentValueNotImplementedException::class, $e); $this->assertStringEndsWith('Only integer Unix timestamps and DateTime objects are supported. Please install the "intl" extension for full localization capabilities.', $e->getMessage()); } @@ -74,7 +78,7 @@ public function testFormatWithUnsupportedTimestampArgument() public function testFormatWithUnimplementedChars() { - $this->expectException(\Symfony\Component\Intl\Exception\NotImplementedException::class); + $this->expectException(NotImplementedException::class); $pattern = 'Y'; $formatter = $this->getDateFormatter('en', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT, 'UTC', IntlDateFormatter::GREGORIAN, $pattern); $formatter->format(0); @@ -82,7 +86,7 @@ public function testFormatWithUnimplementedChars() public function testFormatWithNonIntegerTimestamp() { - $this->expectException(\Symfony\Component\Intl\Exception\NotImplementedException::class); + $this->expectException(NotImplementedException::class); $formatter = $this->getDefaultDateFormatter(); $formatter->format([]); } @@ -107,14 +111,14 @@ public function testIsLenient() public function testLocaltime() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $formatter = $this->getDefaultDateFormatter(); $formatter->localtime('Wednesday, December 31, 1969 4:00:00 PM PT'); } public function testParseWithNotNullPositionValue() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodArgumentNotImplementedException::class); + $this->expectException(MethodArgumentNotImplementedException::class); $position = 0; $formatter = $this->getDefaultDateFormatter('y'); $this->assertSame(0, $formatter->parse('1970', $position)); @@ -122,27 +126,27 @@ public function testParseWithNotNullPositionValue() public function testSetCalendar() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $formatter = $this->getDefaultDateFormatter(); $formatter->setCalendar(IntlDateFormatter::GREGORIAN); } public function testSetLenient() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException::class); + $this->expectException(MethodArgumentValueNotImplementedException::class); $formatter = $this->getDefaultDateFormatter(); $formatter->setLenient(true); } public function testFormatWithGmtTimeZoneAndMinutesOffset() { - $this->expectException(\Symfony\Component\Intl\Exception\NotImplementedException::class); + $this->expectException(NotImplementedException::class); parent::testFormatWithGmtTimeZoneAndMinutesOffset(); } public function testFormatWithNonStandardTimezone() { - $this->expectException(\Symfony\Component\Intl\Exception\NotImplementedException::class); + $this->expectException(NotImplementedException::class); parent::testFormatWithNonStandardTimezone(); } diff --git a/src/Symfony/Component/Intl/Tests/IntlTest.php b/src/Symfony/Component/Intl/Tests/IntlTest.php index d09e63f69984..9e73fed2069e 100644 --- a/src/Symfony/Component/Intl/Tests/IntlTest.php +++ b/src/Symfony/Component/Intl/Tests/IntlTest.php @@ -13,6 +13,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Intl\Intl; +use Symfony\Component\Intl\ResourceBundle\CurrencyBundleInterface; +use Symfony\Component\Intl\ResourceBundle\LanguageBundleInterface; +use Symfony\Component\Intl\ResourceBundle\LocaleBundleInterface; +use Symfony\Component\Intl\ResourceBundle\RegionBundleInterface; class IntlTest extends TestCase { @@ -45,7 +49,7 @@ public function testIsExtensionLoadedChecksIfIntlExtensionIsLoaded() */ public function testGetCurrencyBundleCreatesTheCurrencyBundle() { - $this->assertInstanceOf(\Symfony\Component\Intl\ResourceBundle\CurrencyBundleInterface::class, Intl::getCurrencyBundle()); + $this->assertInstanceOf(CurrencyBundleInterface::class, Intl::getCurrencyBundle()); } /** @@ -53,7 +57,7 @@ public function testGetCurrencyBundleCreatesTheCurrencyBundle() */ public function testGetLanguageBundleCreatesTheLanguageBundle() { - $this->assertInstanceOf(\Symfony\Component\Intl\ResourceBundle\LanguageBundleInterface::class, Intl::getLanguageBundle()); + $this->assertInstanceOf(LanguageBundleInterface::class, Intl::getLanguageBundle()); } /** @@ -61,7 +65,7 @@ public function testGetLanguageBundleCreatesTheLanguageBundle() */ public function testGetLocaleBundleCreatesTheLocaleBundle() { - $this->assertInstanceOf(\Symfony\Component\Intl\ResourceBundle\LocaleBundleInterface::class, Intl::getLocaleBundle()); + $this->assertInstanceOf(LocaleBundleInterface::class, Intl::getLocaleBundle()); } /** @@ -69,7 +73,7 @@ public function testGetLocaleBundleCreatesTheLocaleBundle() */ public function testGetRegionBundleCreatesTheRegionBundle() { - $this->assertInstanceOf(\Symfony\Component\Intl\ResourceBundle\RegionBundleInterface::class, Intl::getRegionBundle()); + $this->assertInstanceOf(RegionBundleInterface::class, Intl::getRegionBundle()); } public function testGetIcuVersionReadsTheVersionOfInstalledIcuLibrary() diff --git a/src/Symfony/Component/Intl/Tests/Locale/LocaleTest.php b/src/Symfony/Component/Intl/Tests/Locale/LocaleTest.php index cb2114695390..80b3352e21d3 100644 --- a/src/Symfony/Component/Intl/Tests/Locale/LocaleTest.php +++ b/src/Symfony/Component/Intl/Tests/Locale/LocaleTest.php @@ -11,13 +11,14 @@ namespace Symfony\Component\Intl\Tests\Locale; +use Symfony\Component\Intl\Exception\MethodNotImplementedException; use Symfony\Component\Intl\Locale\Locale; class LocaleTest extends AbstractLocaleTest { public function testAcceptFromHttp() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('acceptFromHttp', 'pt-br,en-us;q=0.7,en;q=0.5'); } @@ -34,7 +35,7 @@ public function testCanonicalize() public function testComposeLocale() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $subtags = [ 'language' => 'pt', 'script' => 'Latn', @@ -45,73 +46,73 @@ public function testComposeLocale() public function testFilterMatches() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('filterMatches', 'pt-BR', 'pt-BR'); } public function testGetAllVariants() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('getAllVariants', 'pt_BR_Latn'); } public function testGetDisplayLanguage() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('getDisplayLanguage', 'pt-Latn-BR', 'en'); } public function testGetDisplayName() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('getDisplayName', 'pt-Latn-BR', 'en'); } public function testGetDisplayRegion() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('getDisplayRegion', 'pt-Latn-BR', 'en'); } public function testGetDisplayScript() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('getDisplayScript', 'pt-Latn-BR', 'en'); } public function testGetDisplayVariant() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('getDisplayVariant', 'pt-Latn-BR', 'en'); } public function testGetKeywords() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('getKeywords', 'pt-BR@currency=BRL'); } public function testGetPrimaryLanguage() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('getPrimaryLanguage', 'pt-Latn-BR'); } public function testGetRegion() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('getRegion', 'pt-Latn-BR'); } public function testGetScript() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('getScript', 'pt-Latn-BR'); } public function testLookup() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $langtag = [ 'pt-Latn-BR', 'pt-BR', @@ -121,13 +122,13 @@ public function testLookup() public function testParseLocale() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('parseLocale', 'pt-Latn-BR'); } public function testSetDefault() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $this->call('setDefault', 'pt_BR'); } diff --git a/src/Symfony/Component/Intl/Tests/LocalesTest.php b/src/Symfony/Component/Intl/Tests/LocalesTest.php index c351e7ac82c2..5e3279622bfb 100644 --- a/src/Symfony/Component/Intl/Tests/LocalesTest.php +++ b/src/Symfony/Component/Intl/Tests/LocalesTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Intl\Tests; +use Symfony\Component\Intl\Exception\MissingResourceException; use Symfony\Component\Intl\Locales; /** @@ -86,7 +87,7 @@ public function testGetNameDefaultLocale() public function testGetNameWithInvalidLocale() { - $this->expectException(\Symfony\Component\Intl\Exception\MissingResourceException::class); + $this->expectException(MissingResourceException::class); Locales::getName('foo'); } diff --git a/src/Symfony/Component/Intl/Tests/NumberFormatter/NumberFormatterTest.php b/src/Symfony/Component/Intl/Tests/NumberFormatter/NumberFormatterTest.php index f6190db76e3f..c3f49194360c 100644 --- a/src/Symfony/Component/Intl/Tests/NumberFormatter/NumberFormatterTest.php +++ b/src/Symfony/Component/Intl/Tests/NumberFormatter/NumberFormatterTest.php @@ -11,6 +11,10 @@ namespace Symfony\Component\Intl\Tests\NumberFormatter; +use Symfony\Component\Intl\Exception\MethodArgumentNotImplementedException; +use Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException; +use Symfony\Component\Intl\Exception\MethodNotImplementedException; +use Symfony\Component\Intl\Exception\NotImplementedException; use Symfony\Component\Intl\Globals\IntlGlobals; use Symfony\Component\Intl\NumberFormatter\NumberFormatter; @@ -22,32 +26,32 @@ class NumberFormatterTest extends AbstractNumberFormatterTest { public function testConstructorWithUnsupportedLocale() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException::class); + $this->expectException(MethodArgumentValueNotImplementedException::class); $this->getNumberFormatter('pt_BR'); } public function testConstructorWithUnsupportedStyle() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException::class); + $this->expectException(MethodArgumentValueNotImplementedException::class); $this->getNumberFormatter('en', NumberFormatter::PATTERN_DECIMAL); } public function testConstructorWithPatternDifferentThanNull() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodArgumentNotImplementedException::class); + $this->expectException(MethodArgumentNotImplementedException::class); $this->getNumberFormatter('en', NumberFormatter::DECIMAL, ''); } public function testSetAttributeWithUnsupportedAttribute() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException::class); + $this->expectException(MethodArgumentValueNotImplementedException::class); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->setAttribute(NumberFormatter::LENIENT_PARSE, null); } public function testSetAttributeInvalidRoundingMode() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException::class); + $this->expectException(MethodArgumentValueNotImplementedException::class); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->setAttribute(NumberFormatter::ROUNDING_MODE, -1); } @@ -74,7 +78,7 @@ public function testFormatWithCurrencyStyle() */ public function testFormatTypeInt32($formatter, $value, $expected, $message = '') { - $this->expectException(\Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException::class); + $this->expectException(MethodArgumentValueNotImplementedException::class); parent::testFormatTypeInt32($formatter, $value, $expected, $message); } @@ -83,7 +87,7 @@ public function testFormatTypeInt32($formatter, $value, $expected, $message = '' */ public function testFormatTypeInt32WithCurrencyStyle($formatter, $value, $expected, $message = '') { - $this->expectException(\Symfony\Component\Intl\Exception\NotImplementedException::class); + $this->expectException(NotImplementedException::class); parent::testFormatTypeInt32WithCurrencyStyle($formatter, $value, $expected, $message); } @@ -92,7 +96,7 @@ public function testFormatTypeInt32WithCurrencyStyle($formatter, $value, $expect */ public function testFormatTypeInt64($formatter, $value, $expected) { - $this->expectException(\Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException::class); + $this->expectException(MethodArgumentValueNotImplementedException::class); parent::testFormatTypeInt64($formatter, $value, $expected); } @@ -101,7 +105,7 @@ public function testFormatTypeInt64($formatter, $value, $expected) */ public function testFormatTypeInt64WithCurrencyStyle($formatter, $value, $expected) { - $this->expectException(\Symfony\Component\Intl\Exception\NotImplementedException::class); + $this->expectException(NotImplementedException::class); parent::testFormatTypeInt64WithCurrencyStyle($formatter, $value, $expected); } @@ -110,7 +114,7 @@ public function testFormatTypeInt64WithCurrencyStyle($formatter, $value, $expect */ public function testFormatTypeDouble($formatter, $value, $expected) { - $this->expectException(\Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException::class); + $this->expectException(MethodArgumentValueNotImplementedException::class); parent::testFormatTypeDouble($formatter, $value, $expected); } @@ -119,13 +123,13 @@ public function testFormatTypeDouble($formatter, $value, $expected) */ public function testFormatTypeDoubleWithCurrencyStyle($formatter, $value, $expected) { - $this->expectException(\Symfony\Component\Intl\Exception\NotImplementedException::class); + $this->expectException(NotImplementedException::class); parent::testFormatTypeDoubleWithCurrencyStyle($formatter, $value, $expected); } public function testGetPattern() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->getPattern(); } @@ -138,28 +142,28 @@ public function testGetErrorCode() public function testParseCurrency() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->parseCurrency(null, $currency); } public function testSetPattern() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->setPattern(null); } public function testSetSymbol() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->setSymbol(null, null); } public function testSetTextAttribute() { - $this->expectException(\Symfony\Component\Intl\Exception\MethodNotImplementedException::class); + $this->expectException(MethodNotImplementedException::class); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->setTextAttribute(null, null); } diff --git a/src/Symfony/Component/Intl/Tests/ScriptsTest.php b/src/Symfony/Component/Intl/Tests/ScriptsTest.php index 62981299ad10..1cf350df960e 100644 --- a/src/Symfony/Component/Intl/Tests/ScriptsTest.php +++ b/src/Symfony/Component/Intl/Tests/ScriptsTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Intl\Tests; +use Symfony\Component\Intl\Exception\MissingResourceException; use Symfony\Component\Intl\Scripts; /** @@ -280,7 +281,7 @@ public function testGetNameDefaultLocale() public function testGetNameWithInvalidScriptCode() { - $this->expectException(\Symfony\Component\Intl\Exception\MissingResourceException::class); + $this->expectException(MissingResourceException::class); Scripts::getName('foo'); } diff --git a/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/EntryManagerTest.php b/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/EntryManagerTest.php index ffd938295df0..d3ba6d1a99ac 100644 --- a/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/EntryManagerTest.php +++ b/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/EntryManagerTest.php @@ -14,12 +14,14 @@ use Symfony\Component\Ldap\Adapter\ExtLdap\Connection; use Symfony\Component\Ldap\Adapter\ExtLdap\EntryManager; use Symfony\Component\Ldap\Entry; +use Symfony\Component\Ldap\Exception\LdapException; +use Symfony\Component\Ldap\Exception\NotBoundException; class EntryManagerTest extends TestCase { public function testMove() { - $this->expectException(\Symfony\Component\Ldap\Exception\LdapException::class); + $this->expectException(LdapException::class); $this->expectExceptionMessage('Entry "$$$$$$" malformed, could not parse RDN.'); $connection = $this->createMock(Connection::class); $connection @@ -33,9 +35,9 @@ public function testMove() public function testGetResources() { - $this->expectException(\Symfony\Component\Ldap\Exception\NotBoundException::class); + $this->expectException(NotBoundException::class); $this->expectExceptionMessage('Query execution is not possible without binding the connection first.'); - $connection = $this->getMockBuilder(Connection::class)->getMock(); + $connection = $this->createMock(Connection::class); $connection ->expects($this->once()) ->method('isBound')->willReturn(false); diff --git a/src/Symfony/Component/Ldap/Tests/LdapTest.php b/src/Symfony/Component/Ldap/Tests/LdapTest.php index 881a15a4b29e..db543d34ebcd 100644 --- a/src/Symfony/Component/Ldap/Tests/LdapTest.php +++ b/src/Symfony/Component/Ldap/Tests/LdapTest.php @@ -29,13 +29,13 @@ class LdapTest extends TestCase protected function setUp(): void { - $this->adapter = $this->getMockBuilder(AdapterInterface::class)->getMock(); + $this->adapter = $this->createMock(AdapterInterface::class); $this->ldap = new Ldap($this->adapter); } public function testLdapBind() { - $connection = $this->getMockBuilder(ConnectionInterface::class)->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection ->expects($this->once()) ->method('bind') diff --git a/src/Symfony/Component/Ldap/Tests/Security/LdapUserProviderTest.php b/src/Symfony/Component/Ldap/Tests/Security/LdapUserProviderTest.php index a2e888077cde..f6cd4c7414c5 100644 --- a/src/Symfony/Component/Ldap/Tests/Security/LdapUserProviderTest.php +++ b/src/Symfony/Component/Ldap/Tests/Security/LdapUserProviderTest.php @@ -19,6 +19,8 @@ use Symfony\Component\Ldap\LdapInterface; use Symfony\Component\Ldap\Security\LdapUser; use Symfony\Component\Ldap\Security\LdapUserProvider; +use Symfony\Component\Security\Core\Exception\InvalidArgumentException; +use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; /** * @requires extension ldap @@ -27,7 +29,7 @@ class LdapUserProviderTest extends TestCase { public function testLoadUserByUsernameFailsIfCantConnectToLdap() { - $this->expectException(\Symfony\Component\Security\Core\Exception\UsernameNotFoundException::class); + $this->expectException(UsernameNotFoundException::class); $ldap = $this->createMock(LdapInterface::class); $ldap @@ -42,7 +44,7 @@ public function testLoadUserByUsernameFailsIfCantConnectToLdap() public function testLoadUserByUsernameFailsIfNoLdapEntries() { - $this->expectException(\Symfony\Component\Security\Core\Exception\UsernameNotFoundException::class); + $this->expectException(UsernameNotFoundException::class); $result = $this->createMock(CollectionInterface::class); $query = $this->createMock(QueryInterface::class); @@ -74,7 +76,7 @@ public function testLoadUserByUsernameFailsIfNoLdapEntries() public function testLoadUserByUsernameFailsIfMoreThanOneLdapEntry() { - $this->expectException(\Symfony\Component\Security\Core\Exception\UsernameNotFoundException::class); + $this->expectException(UsernameNotFoundException::class); $result = $this->createMock(CollectionInterface::class); $query = $this->createMock(QueryInterface::class); @@ -106,7 +108,7 @@ public function testLoadUserByUsernameFailsIfMoreThanOneLdapEntry() public function testLoadUserByUsernameFailsIfMoreThanOneLdapPasswordsInEntry() { - $this->expectException(\Symfony\Component\Security\Core\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $result = $this->createMock(CollectionInterface::class); $query = $this->createMock(QueryInterface::class); @@ -183,7 +185,7 @@ public function testLoadUserByUsernameShouldNotFailIfEntryHasNoUidKeyAttribute() public function testLoadUserByUsernameFailsIfEntryHasNoPasswordAttribute() { - $this->expectException(\Symfony\Component\Security\Core\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $result = $this->createMock(CollectionInterface::class); $query = $this->createMock(QueryInterface::class); diff --git a/src/Symfony/Component/Lock/Tests/FactoryTest.php b/src/Symfony/Component/Lock/Tests/FactoryTest.php index d67949098c7a..af5f8c488c75 100644 --- a/src/Symfony/Component/Lock/Tests/FactoryTest.php +++ b/src/Symfony/Component/Lock/Tests/FactoryTest.php @@ -24,8 +24,8 @@ class FactoryTest extends TestCase { public function testCreateLock() { - $store = $this->getMockBuilder(StoreInterface::class)->getMock(); - $logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); + $store = $this->createMock(StoreInterface::class); + $logger = $this->createMock(LoggerInterface::class); $factory = new Factory($store); $factory->setLogger($logger); diff --git a/src/Symfony/Component/Lock/Tests/LockFactoryTest.php b/src/Symfony/Component/Lock/Tests/LockFactoryTest.php index a867b8cfaefd..6e73cfc2573e 100644 --- a/src/Symfony/Component/Lock/Tests/LockFactoryTest.php +++ b/src/Symfony/Component/Lock/Tests/LockFactoryTest.php @@ -25,8 +25,8 @@ class LockFactoryTest extends TestCase { public function testCreateLock() { - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); - $logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); + $logger = $this->createMock(LoggerInterface::class); $factory = new LockFactory($store); $factory->setLogger($logger); @@ -40,8 +40,8 @@ public function testCreateLock() */ public function testCreateLockWithLegacyStoreImplementation() { - $store = $this->getMockBuilder(StoreInterface::class)->getMock(); - $logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); + $store = $this->createMock(StoreInterface::class); + $logger = $this->createMock(LoggerInterface::class); $factory = new LockFactory($store); $factory->setLogger($logger); diff --git a/src/Symfony/Component/Lock/Tests/LockTest.php b/src/Symfony/Component/Lock/Tests/LockTest.php index 5c218e5ea75a..dd74f6d04ef4 100644 --- a/src/Symfony/Component/Lock/Tests/LockTest.php +++ b/src/Symfony/Component/Lock/Tests/LockTest.php @@ -15,6 +15,7 @@ use Psr\Log\LoggerInterface; use Symfony\Component\Lock\BlockingStoreInterface; use Symfony\Component\Lock\Exception\LockConflictedException; +use Symfony\Component\Lock\Exception\LockReleasingException; use Symfony\Component\Lock\Key; use Symfony\Component\Lock\Lock; use Symfony\Component\Lock\PersistingStoreInterface; @@ -29,7 +30,7 @@ class LockTest extends TestCase public function testAcquireNoBlocking() { $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store); $store @@ -45,7 +46,7 @@ public function testAcquireNoBlocking() public function testAcquireNoBlockingStoreInterface() { $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store); $store @@ -64,7 +65,7 @@ public function testAcquireNoBlockingStoreInterface() public function testPassingOldStoreInterface() { $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(StoreInterface::class)->getMock(); + $store = $this->createMock(StoreInterface::class); $lock = new Lock($key, $store); $store @@ -80,7 +81,7 @@ public function testPassingOldStoreInterface() public function testAcquireReturnsFalse() { $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store); $store @@ -97,7 +98,7 @@ public function testAcquireReturnsFalse() public function testAcquireReturnsFalseStoreInterface() { $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store); $store @@ -133,7 +134,7 @@ public function testAcquireBlocking() public function testAcquireSetsTtl() { $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store, 10); $store @@ -153,7 +154,7 @@ public function testAcquireSetsTtl() public function testRefresh() { $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store, 10); $store @@ -170,7 +171,7 @@ public function testRefresh() public function testRefreshCustom() { $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store, 10); $store @@ -187,7 +188,7 @@ public function testRefreshCustom() public function testIsAquired() { $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store, 10); $store @@ -201,7 +202,7 @@ public function testIsAquired() public function testRelease() { $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store, 10); $store @@ -221,7 +222,7 @@ public function testRelease() public function testReleaseStoreInterface() { $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store, 10); $store @@ -278,9 +279,9 @@ public function testNoAutoReleaseWhenNotConfigured() public function testReleaseThrowsExceptionWhenDeletionFail() { - $this->expectException(\Symfony\Component\Lock\Exception\LockReleasingException::class); + $this->expectException(LockReleasingException::class); $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store, 10); $store @@ -299,9 +300,9 @@ public function testReleaseThrowsExceptionWhenDeletionFail() public function testReleaseThrowsExceptionIfNotWellDeleted() { - $this->expectException(\Symfony\Component\Lock\Exception\LockReleasingException::class); + $this->expectException(LockReleasingException::class); $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store, 10); $store @@ -320,10 +321,10 @@ public function testReleaseThrowsExceptionIfNotWellDeleted() public function testReleaseThrowsAndLog() { - $this->expectException(\Symfony\Component\Lock\Exception\LockReleasingException::class); + $this->expectException(LockReleasingException::class); $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); - $logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); + $logger = $this->createMock(LoggerInterface::class); $lock = new Lock($key, $store, 10, true); $lock->setLogger($logger); @@ -351,7 +352,7 @@ public function testReleaseThrowsAndLog() public function testExpiration($ttls, $expected) { $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store, 10); foreach ($ttls as $ttl) { @@ -370,7 +371,7 @@ public function testExpiration($ttls, $expected) public function testExpirationStoreInterface($ttls, $expected) { $key = new Key(uniqid(__METHOD__, true)); - $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store = $this->createMock(PersistingStoreInterface::class); $lock = new Lock($key, $store, 10); foreach ($ttls as $ttl) { diff --git a/src/Symfony/Component/Lock/Tests/Store/CombinedStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/CombinedStoreTest.php index 7d99826b3c44..f24f0aa9fa90 100644 --- a/src/Symfony/Component/Lock/Tests/Store/CombinedStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/CombinedStoreTest.php @@ -62,7 +62,7 @@ public function getStore(): PersistingStoreInterface protected function setUp(): void { - $this->strategy = $this->getMockBuilder(StrategyInterface::class)->getMock(); + $this->strategy = $this->createMock(StrategyInterface::class); $this->store1 = $this->createMock(BlockingStoreInterface::class); $this->store2 = $this->createMock(BlockingStoreInterface::class); @@ -264,8 +264,8 @@ public function testputOffExpirationAbortWhenStrategyCantBeMet() public function testPutOffExpirationIgnoreNonExpiringStorage() { - $store1 = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); - $store2 = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); + $store1 = $this->createMock(PersistingStoreInterface::class); + $store2 = $this->createMock(PersistingStoreInterface::class); $store = new CombinedStore([$store1, $store2], $this->strategy); diff --git a/src/Symfony/Component/Lock/Tests/Store/FlockStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/FlockStoreTest.php index 463ddc1b7556..9ca9a4373d87 100644 --- a/src/Symfony/Component/Lock/Tests/Store/FlockStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/FlockStoreTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Lock\Tests\Store; +use Symfony\Component\Lock\Exception\InvalidArgumentException; use Symfony\Component\Lock\Key; use Symfony\Component\Lock\PersistingStoreInterface; use Symfony\Component\Lock\Store\FlockStore; @@ -32,7 +33,7 @@ protected function getStore(): PersistingStoreInterface public function testConstructWhenRepositoryDoesNotExist() { - $this->expectException(\Symfony\Component\Lock\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The directory "/a/b/c/d/e" is not writable.'); if (!getenv('USER') || 'root' === getenv('USER')) { $this->markTestSkipped('This test will fail if run under superuser'); @@ -43,7 +44,7 @@ public function testConstructWhenRepositoryDoesNotExist() public function testConstructWhenRepositoryIsNotWriteable() { - $this->expectException(\Symfony\Component\Lock\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The directory "/" is not writable.'); if (!getenv('USER') || 'root' === getenv('USER')) { $this->markTestSkipped('This test will fail if run under superuser'); diff --git a/src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php index caf62353cd2e..fa93d0c5701c 100644 --- a/src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Lock\Tests\Store; +use Symfony\Component\Lock\Exception\InvalidTtlException; use Symfony\Component\Lock\Key; use Symfony\Component\Lock\PersistingStoreInterface; use Symfony\Component\Lock\Store\MemcachedStore; @@ -63,7 +64,7 @@ public function testAbortAfterExpiration() public function testInvalidTtl() { - $this->expectException(\Symfony\Component\Lock\Exception\InvalidTtlException::class); + $this->expectException(InvalidTtlException::class); $store = $this->getStore(); $store->putOffExpiration(new Key('toto'), 0.1); } diff --git a/src/Symfony/Component/Lock/Tests/Store/PdoStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/PdoStoreTest.php index 02cc3461cba8..2d7cf1035ebc 100644 --- a/src/Symfony/Component/Lock/Tests/Store/PdoStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/PdoStoreTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Lock\Tests\Store; +use Symfony\Component\Lock\Exception\InvalidTtlException; use Symfony\Component\Lock\Key; use Symfony\Component\Lock\PersistingStoreInterface; use Symfony\Component\Lock\Store\PdoStore; @@ -62,14 +63,14 @@ public function testAbortAfterExpiration() public function testInvalidTtl() { - $this->expectException(\Symfony\Component\Lock\Exception\InvalidTtlException::class); + $this->expectException(InvalidTtlException::class); $store = $this->getStore(); $store->putOffExpiration(new Key('toto'), 0.1); } public function testInvalidTtlConstruct() { - $this->expectException(\Symfony\Component\Lock\Exception\InvalidTtlException::class); + $this->expectException(InvalidTtlException::class); return new PdoStore('sqlite:'.self::$dbFile, [], 0.1, 0.1); } diff --git a/src/Symfony/Component/Lock/Tests/Store/RedisStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/RedisStoreTest.php index cc0b02afcf8f..acec9c402982 100644 --- a/src/Symfony/Component/Lock/Tests/Store/RedisStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/RedisStoreTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Lock\Tests\Store; +use Symfony\Component\Lock\Exception\InvalidTtlException; use Symfony\Component\Lock\Store\RedisStore; /** @@ -40,7 +41,7 @@ protected function getRedisConnection() public function testInvalidTtl() { - $this->expectException(\Symfony\Component\Lock\Exception\InvalidTtlException::class); + $this->expectException(InvalidTtlException::class); new RedisStore($this->getRedisConnection(), -1); } } diff --git a/src/Symfony/Component/Mailer/Tests/Transport/Smtp/Stream/SocketStreamTest.php b/src/Symfony/Component/Mailer/Tests/Transport/Smtp/Stream/SocketStreamTest.php index 33e939d9b60b..e4ca6aa45eca 100644 --- a/src/Symfony/Component/Mailer/Tests/Transport/Smtp/Stream/SocketStreamTest.php +++ b/src/Symfony/Component/Mailer/Tests/Transport/Smtp/Stream/SocketStreamTest.php @@ -12,13 +12,14 @@ namespace Symfony\Component\Mailer\Tests\Transport\Smtp\Stream; use PHPUnit\Framework\TestCase; +use Symfony\Component\Mailer\Exception\TransportException; use Symfony\Component\Mailer\Transport\Smtp\Stream\SocketStream; class SocketStreamTest extends TestCase { public function testSocketErrorNoConnection() { - $this->expectException(\Symfony\Component\Mailer\Exception\TransportException::class); + $this->expectException(TransportException::class); $this->expectExceptionMessageMatches('/Connection refused|unable to connect/'); $s = new SocketStream(); $s->setTimeout(0.1); @@ -28,7 +29,7 @@ public function testSocketErrorNoConnection() public function testSocketErrorBeforeConnectError() { - $this->expectException(\Symfony\Component\Mailer\Exception\TransportException::class); + $this->expectException(TransportException::class); $this->expectExceptionMessageMatches('/no valid certs found cafile stream|Unable to find the socket transport "ssl"/'); $s = new SocketStream(); $s->setStreamOptions([ diff --git a/src/Symfony/Component/Messenger/Test/Middleware/MiddlewareTestCase.php b/src/Symfony/Component/Messenger/Test/Middleware/MiddlewareTestCase.php index fc5d7d859ad0..08c3d6adb712 100644 --- a/src/Symfony/Component/Messenger/Test/Middleware/MiddlewareTestCase.php +++ b/src/Symfony/Component/Messenger/Test/Middleware/MiddlewareTestCase.php @@ -34,7 +34,7 @@ protected function getStackMock(bool $nextIsCalled = true) return $stack; } - $nextMiddleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock(); + $nextMiddleware = $this->createMock(MiddlewareInterface::class); $nextMiddleware ->expects($this->once()) ->method('handle') @@ -48,7 +48,7 @@ protected function getStackMock(bool $nextIsCalled = true) protected function getThrowingStackMock(\Throwable $throwable = null) { - $nextMiddleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock(); + $nextMiddleware = $this->createMock(MiddlewareInterface::class); $nextMiddleware ->expects($this->once()) ->method('handle') diff --git a/src/Symfony/Component/Messenger/Tests/Command/DebugCommandTest.php b/src/Symfony/Component/Messenger/Tests/Command/DebugCommandTest.php index 6d1503521b8a..790f1b462026 100644 --- a/src/Symfony/Component/Messenger/Tests/Command/DebugCommandTest.php +++ b/src/Symfony/Component/Messenger/Tests/Command/DebugCommandTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Messenger\Tests\Command; use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Exception\RuntimeException; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\Messenger\Command\DebugCommand; use Symfony\Component\Messenger\Tests\Fixtures\DummyCommand; @@ -141,7 +142,7 @@ public function testOutputWithoutMessages() public function testExceptionOnUnknownBusArgument() { - $this->expectException(\Symfony\Component\Console\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Bus "unknown_bus" does not exist. Known buses are "command_bus", "query_bus".'); $command = new DebugCommand(['command_bus' => [], 'query_bus' => []]); diff --git a/src/Symfony/Component/Messenger/Tests/DataCollector/MessengerDataCollectorTest.php b/src/Symfony/Component/Messenger/Tests/DataCollector/MessengerDataCollectorTest.php index 39089131daa4..a920e30125b4 100644 --- a/src/Symfony/Component/Messenger/Tests/DataCollector/MessengerDataCollectorTest.php +++ b/src/Symfony/Component/Messenger/Tests/DataCollector/MessengerDataCollectorTest.php @@ -39,7 +39,7 @@ public function testHandle() $message = new DummyMessage('dummy message'); $envelope = new Envelope($message); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $bus->method('dispatch')->with($message)->willReturn($envelope); $bus = new TraceableMessageBus($bus); @@ -80,7 +80,7 @@ public function testHandleWithException() { $message = new DummyMessage('dummy message'); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $bus->method('dispatch')->with($message)->willThrowException(new \RuntimeException('foo')); $bus = new TraceableMessageBus($bus); @@ -127,11 +127,11 @@ public function testHandleWithException() public function testKeepsOrderedDispatchCalls() { - $firstBus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $firstBus = $this->createMock(MessageBusInterface::class); $firstBus->method('dispatch')->willReturn(new Envelope(new \stdClass())); $firstBus = new TraceableMessageBus($firstBus); - $secondBus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $secondBus = $this->createMock(MessageBusInterface::class); $secondBus->method('dispatch')->willReturn(new Envelope(new \stdClass())); $secondBus = new TraceableMessageBus($secondBus); diff --git a/src/Symfony/Component/Messenger/Tests/DependencyInjection/MessengerPassTest.php b/src/Symfony/Component/Messenger/Tests/DependencyInjection/MessengerPassTest.php index b3c35c7770fc..940c32b37474 100644 --- a/src/Symfony/Component/Messenger/Tests/DependencyInjection/MessengerPassTest.php +++ b/src/Symfony/Component/Messenger/Tests/DependencyInjection/MessengerPassTest.php @@ -15,6 +15,7 @@ use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass; use Symfony\Component\DependencyInjection\Compiler\ResolveClassPass; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ServiceLocator; use Symfony\Component\Messenger\Command\ConsumeMessagesCommand; @@ -155,7 +156,7 @@ public function testProcessHandlersByBus() public function testProcessTagWithUnknownBus() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\Fixtures\DummyCommandHandler": bus "unknown_bus" specified on the tag "messenger.message_handler" does not exist (known ones are: "command_bus").'); $container = $this->getContainerBuilder($commandBusId = 'command_bus'); @@ -227,7 +228,7 @@ public function testGetClassesAndMethodsAndPrioritiesFromTheSubscriber() public function testThrowsExceptionIfTheHandlerClassDoesNotExist() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid service "NonExistentHandlerClass": class "NonExistentHandlerClass" does not exist.'); $container = $this->getContainerBuilder(); $container->register('message_bus', MessageBusInterface::class)->addTag('messenger.bus'); @@ -241,7 +242,7 @@ public function testThrowsExceptionIfTheHandlerClassDoesNotExist() public function testThrowsExceptionIfTheHandlerMethodDoesNotExist() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\HandlerMappingWithNonExistentMethod": method "Symfony\Component\Messenger\Tests\DependencyInjection\HandlerMappingWithNonExistentMethod::dummyMethod()" does not exist.'); $container = $this->getContainerBuilder(); $container->register('message_bus', MessageBusInterface::class)->addTag('messenger.bus'); @@ -371,7 +372,7 @@ public function testItRegistersHandlersOnDifferentBuses() public function testItThrowsAnExceptionOnUnknownBus() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid configuration returned by method "Symfony\Component\Messenger\Tests\DependencyInjection\HandlerOnUndefinedBus::getHandledMessages()" for message "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage": bus "some_undefined_bus" does not exist.'); $container = $this->getContainerBuilder(); $container @@ -384,7 +385,7 @@ public function testItThrowsAnExceptionOnUnknownBus() public function testUndefinedMessageClassForHandler() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandler": class or interface "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessage" used as argument type in method "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandler::__invoke()" not found.'); $container = $this->getContainerBuilder(); $container @@ -397,7 +398,7 @@ public function testUndefinedMessageClassForHandler() public function testUndefinedMessageClassForHandlerImplementingMessageHandlerInterface() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandlerViaHandlerInterface": class or interface "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessage" used as argument type in method "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandlerViaHandlerInterface::__invoke()" not found.'); $container = $this->getContainerBuilder(); $container @@ -410,7 +411,7 @@ public function testUndefinedMessageClassForHandlerImplementingMessageHandlerInt public function testUndefinedMessageClassForHandlerImplementingMessageSubscriberInterface() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandlerViaSubscriberInterface": class or interface "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessage" returned by method "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandlerViaSubscriberInterface::getHandledMessages()" not found.'); $container = $this->getContainerBuilder(); $container @@ -423,7 +424,7 @@ public function testUndefinedMessageClassForHandlerImplementingMessageSubscriber public function testNotInvokableHandler() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\NotInvokableHandler": class "Symfony\Component\Messenger\Tests\DependencyInjection\NotInvokableHandler" must have an "__invoke()" method.'); $container = $this->getContainerBuilder(); $container @@ -436,7 +437,7 @@ public function testNotInvokableHandler() public function testMissingArgumentHandler() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\MissingArgumentHandler": method "Symfony\Component\Messenger\Tests\DependencyInjection\MissingArgumentHandler::__invoke()" requires at least one argument, first one being the message it handles.'); $container = $this->getContainerBuilder(); $container @@ -449,7 +450,7 @@ public function testMissingArgumentHandler() public function testMissingArgumentTypeHandler() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\MissingArgumentTypeHandler": argument "$message" of method "Symfony\Component\Messenger\Tests\DependencyInjection\MissingArgumentTypeHandler::__invoke()" must have a type-hint corresponding to the message class it handles.'); $container = $this->getContainerBuilder(); $container @@ -462,7 +463,7 @@ public function testMissingArgumentTypeHandler() public function testBuiltinArgumentTypeHandler() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\BuiltinArgumentTypeHandler": type-hint of argument "$message" in method "Symfony\Component\Messenger\Tests\DependencyInjection\BuiltinArgumentTypeHandler::__invoke()" must be a class , "string" given.'); $container = $this->getContainerBuilder(); $container @@ -475,7 +476,7 @@ public function testBuiltinArgumentTypeHandler() public function testNeedsToHandleAtLeastOneMessage() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\HandleNoMessageHandler": method "Symfony\Component\Messenger\Tests\DependencyInjection\HandleNoMessageHandler::getHandledMessages()" must return one or more messages.'); $container = $this->getContainerBuilder(); $container @@ -554,7 +555,7 @@ public function testRegistersMiddlewareFromServices() public function testCannotRegistersAnUndefinedMiddleware() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid middleware: service "not_defined_middleware" not found.'); $container = $this->getContainerBuilder($fooBusId = 'messenger.bus.foo'); $container->setParameter($middlewareParameter = $fooBusId.'.middleware', [ @@ -566,7 +567,7 @@ public function testCannotRegistersAnUndefinedMiddleware() public function testMiddlewareFactoryDefinitionMustBeAbstract() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid middleware factory "not_an_abstract_definition": a middleware factory must be an abstract definition.'); $container = $this->getContainerBuilder($fooBusId = 'messenger.bus.foo'); $container->register('not_an_abstract_definition', UselessMiddleware::class); diff --git a/src/Symfony/Component/Messenger/Tests/HandleTraitTest.php b/src/Symfony/Component/Messenger/Tests/HandleTraitTest.php index d2b495de2a57..dd3ae59bc6b7 100644 --- a/src/Symfony/Component/Messenger/Tests/HandleTraitTest.php +++ b/src/Symfony/Component/Messenger/Tests/HandleTraitTest.php @@ -4,6 +4,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Messenger\Envelope; +use Symfony\Component\Messenger\Exception\LogicException; use Symfony\Component\Messenger\HandleTrait; use Symfony\Component\Messenger\MessageBus; use Symfony\Component\Messenger\MessageBusInterface; @@ -14,7 +15,7 @@ class HandleTraitTest extends TestCase { public function testItThrowsOnNoMessageBusInstance() { - $this->expectException(\Symfony\Component\Messenger\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('You must provide a "Symfony\Component\Messenger\MessageBusInterface" instance in the "Symfony\Component\Messenger\Tests\TestQueryBus::$messageBus" property, "NULL" given.'); $queryBus = new TestQueryBus(null); $query = new DummyMessage('Hello'); @@ -48,7 +49,7 @@ public function testHandleAcceptsEnvelopes() public function testHandleThrowsOnNoHandledStamp() { - $this->expectException(\Symfony\Component\Messenger\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Message of type "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage" was handled zero times. Exactly one handler is expected when using "Symfony\Component\Messenger\Tests\TestQueryBus::handle()".'); $bus = $this->createMock(MessageBus::class); $queryBus = new TestQueryBus($bus); @@ -61,7 +62,7 @@ public function testHandleThrowsOnNoHandledStamp() public function testHandleThrowsOnMultipleHandledStamps() { - $this->expectException(\Symfony\Component\Messenger\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Message of type "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage" was handled multiple times. Only one handler is expected when using "Symfony\Component\Messenger\Tests\TestQueryBus::handle()", got 2: "FirstDummyHandler::__invoke", "SecondDummyHandler::__invoke".'); $bus = $this->createMock(MessageBus::class); $queryBus = new TestQueryBus($bus); diff --git a/src/Symfony/Component/Messenger/Tests/MessageBusTest.php b/src/Symfony/Component/Messenger/Tests/MessageBusTest.php index 47624777b2bf..703a47219a96 100644 --- a/src/Symfony/Component/Messenger/Tests/MessageBusTest.php +++ b/src/Symfony/Component/Messenger/Tests/MessageBusTest.php @@ -44,7 +44,7 @@ public function testItCallsMiddleware() $message = new DummyMessage('Hello'); $envelope = new Envelope($message); - $firstMiddleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock(); + $firstMiddleware = $this->createMock(MiddlewareInterface::class); $firstMiddleware->expects($this->once()) ->method('handle') ->with($envelope, $this->anything()) @@ -52,7 +52,7 @@ public function testItCallsMiddleware() return $stack->next()->handle($envelope, $stack); }); - $secondMiddleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock(); + $secondMiddleware = $this->createMock(MiddlewareInterface::class); $secondMiddleware->expects($this->once()) ->method('handle') ->with($envelope, $this->anything()) @@ -73,7 +73,7 @@ public function testThatAMiddlewareCanAddSomeStampsToTheEnvelope() $envelope = new Envelope($message, [new ReceivedStamp('transport')]); $envelopeWithAnotherStamp = $envelope->with(new AnEnvelopeStamp()); - $firstMiddleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock(); + $firstMiddleware = $this->createMock(MiddlewareInterface::class); $firstMiddleware->expects($this->once()) ->method('handle') ->with($envelope, $this->anything()) @@ -81,7 +81,7 @@ public function testThatAMiddlewareCanAddSomeStampsToTheEnvelope() return $stack->next()->handle($envelope->with(new AnEnvelopeStamp()), $stack); }); - $secondMiddleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock(); + $secondMiddleware = $this->createMock(MiddlewareInterface::class); $secondMiddleware->expects($this->once()) ->method('handle') ->with($envelopeWithAnotherStamp, $this->anything()) @@ -89,7 +89,7 @@ public function testThatAMiddlewareCanAddSomeStampsToTheEnvelope() return $stack->next()->handle($envelope, $stack); }); - $thirdMiddleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock(); + $thirdMiddleware = $this->createMock(MiddlewareInterface::class); $thirdMiddleware->expects($this->once()) ->method('handle') ->with($envelopeWithAnotherStamp, $this->anything()) @@ -113,7 +113,7 @@ public function testThatAMiddlewareCanUpdateTheMessageWhileKeepingTheEnvelopeSta $changedMessage = new DummyMessage('Changed'); $expectedEnvelope = new Envelope($changedMessage, $stamps); - $firstMiddleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock(); + $firstMiddleware = $this->createMock(MiddlewareInterface::class); $firstMiddleware->expects($this->once()) ->method('handle') ->with($envelope, $this->anything()) @@ -121,7 +121,7 @@ public function testThatAMiddlewareCanUpdateTheMessageWhileKeepingTheEnvelopeSta return $stack->next()->handle($expectedEnvelope, $stack); }); - $secondMiddleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock(); + $secondMiddleware = $this->createMock(MiddlewareInterface::class); $secondMiddleware->expects($this->once()) ->method('handle') ->with($expectedEnvelope, $this->anything()) diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/HandleMessageMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/HandleMessageMiddlewareTest.php index 3808843de220..c33bad5137d8 100644 --- a/src/Symfony/Component/Messenger/Tests/Middleware/HandleMessageMiddlewareTest.php +++ b/src/Symfony/Component/Messenger/Tests/Middleware/HandleMessageMiddlewareTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Messenger\Envelope; use Symfony\Component\Messenger\Exception\HandlerFailedException; +use Symfony\Component\Messenger\Exception\NoHandlerForMessageException; use Symfony\Component\Messenger\Handler\HandlerDescriptor; use Symfony\Component\Messenger\Handler\HandlersLocator; use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware; @@ -115,7 +116,7 @@ public function itAddsHandledStampsProvider(): iterable public function testThrowsNoHandlerException() { - $this->expectException(\Symfony\Component\Messenger\Exception\NoHandlerForMessageException::class); + $this->expectException(NoHandlerForMessageException::class); $this->expectExceptionMessage('No handler for message "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage"'); $middleware = new HandleMessageMiddleware(new HandlersLocator([])); diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/SendMessageMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/SendMessageMiddlewareTest.php index b14d8a60a77a..0f5c3af14c61 100644 --- a/src/Symfony/Component/Messenger/Tests/Middleware/SendMessageMiddlewareTest.php +++ b/src/Symfony/Component/Messenger/Tests/Middleware/SendMessageMiddlewareTest.php @@ -31,7 +31,7 @@ public function testItSendsTheMessageToAssignedSender() { $message = new DummyMessage('Hey'); $envelope = new Envelope($message); - $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); + $sender = $this->createMock(SenderInterface::class); $sendersLocator = $this->createSendersLocator([DummyMessage::class => ['my_sender']], ['my_sender' => $sender]); $middleware = new SendMessageMiddleware($sendersLocator); @@ -49,8 +49,8 @@ public function testItSendsTheMessageToAssignedSender() public function testItSendsTheMessageToMultipleSenders() { $envelope = new Envelope(new DummyMessage('Hey')); - $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); - $sender2 = $this->getMockBuilder(SenderInterface::class)->getMock(); + $sender = $this->createMock(SenderInterface::class); + $sender2 = $this->createMock(SenderInterface::class); $sendersLocator = $this->createSendersLocator([DummyMessage::class => ['foo', 'bar']], ['foo' => $sender, 'bar' => $sender2]); $middleware = new SendMessageMiddleware($sendersLocator); @@ -86,7 +86,7 @@ public function testItSendsTheMessageToMultipleSenders() public function testItSendsTheMessageToAssignedSenderWithPreWrappedMessage() { $envelope = new Envelope(new ChildDummyMessage('Hey')); - $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); + $sender = $this->createMock(SenderInterface::class); $sendersLocator = $this->createSendersLocator([DummyMessage::class => ['foo_sender']], ['foo_sender' => $sender]); $middleware = new SendMessageMiddleware($sendersLocator); @@ -100,7 +100,7 @@ public function testItSendsTheMessageBasedOnTheMessageParentClass() { $message = new ChildDummyMessage('Hey'); $envelope = new Envelope($message); - $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); + $sender = $this->createMock(SenderInterface::class); $sendersLocator = $this->createSendersLocator([DummyMessage::class => ['foo_sender']], ['foo_sender' => $sender]); $middleware = new SendMessageMiddleware($sendersLocator); @@ -114,7 +114,7 @@ public function testItSendsTheMessageBasedOnTheMessageInterface() { $message = new DummyMessage('Hey'); $envelope = new Envelope($message); - $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); + $sender = $this->createMock(SenderInterface::class); $sendersLocator = $this->createSendersLocator([DummyMessageInterface::class => ['foo_sender']], ['foo_sender' => $sender]); $middleware = new SendMessageMiddleware($sendersLocator); @@ -128,7 +128,7 @@ public function testItSendsTheMessageBasedOnWildcard() { $message = new DummyMessage('Hey'); $envelope = new Envelope($message); - $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); + $sender = $this->createMock(SenderInterface::class); $sendersLocator = $this->createSendersLocator(['*' => ['foo_sender']], ['foo_sender' => $sender]); $middleware = new SendMessageMiddleware($sendersLocator); @@ -152,7 +152,7 @@ public function testItSkipsReceivedMessages() { $envelope = (new Envelope(new DummyMessage('Hey')))->with(new ReceivedStamp('transport')); - $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); + $sender = $this->createMock(SenderInterface::class); $sendersLocator = $this->createSendersLocator(['*' => ['foo']], ['foo' => $sender]); $middleware = new SendMessageMiddleware($sendersLocator); @@ -173,8 +173,8 @@ public function testItDispatchesTheEventOneTime() ->method('dispatch') ->with(new SendMessageToTransportsEvent($envelope)); - $sender1 = $this->getMockBuilder(SenderInterface::class)->getMock(); - $sender2 = $this->getMockBuilder(SenderInterface::class)->getMock(); + $sender1 = $this->createMock(SenderInterface::class); + $sender2 = $this->createMock(SenderInterface::class); $sendersLocator = $this->createSendersLocator([DummyMessage::class => ['foo', 'bar']], ['foo' => $sender1, 'bar' => $sender2]); $middleware = new SendMessageMiddleware($sendersLocator, $dispatcher); diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/StackMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/StackMiddlewareTest.php index de7527196047..c08d65a01b15 100644 --- a/src/Symfony/Component/Messenger/Tests/Middleware/StackMiddlewareTest.php +++ b/src/Symfony/Component/Messenger/Tests/Middleware/StackMiddlewareTest.php @@ -21,7 +21,7 @@ class StackMiddlewareTest extends TestCase { public function testClone() { - $middleware1 = $this->getMockBuilder(MiddlewareInterface::class)->getMock(); + $middleware1 = $this->createMock(MiddlewareInterface::class); $middleware1 ->expects($this->once()) ->method('handle') @@ -35,7 +35,7 @@ public function testClone() }) ; - $middleware2 = $this->getMockBuilder(MiddlewareInterface::class)->getMock(); + $middleware2 = $this->createMock(MiddlewareInterface::class); $middleware2 ->expects($this->exactly(2)) ->method('handle') diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/TraceableMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/TraceableMiddlewareTest.php index 08e4fd5b695d..65287f4972aa 100644 --- a/src/Symfony/Component/Messenger/Tests/Middleware/TraceableMiddlewareTest.php +++ b/src/Symfony/Component/Messenger/Tests/Middleware/TraceableMiddlewareTest.php @@ -70,7 +70,7 @@ public function testHandleWithException() $this->expectExceptionMessage('Thrown from next middleware.'); $busId = 'command_bus'; - $middleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock(); + $middleware = $this->createMock(MiddlewareInterface::class); $middleware->expects($this->once()) ->method('handle') ->willThrowException(new \RuntimeException('Thrown from next middleware.')) diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/ValidationMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/ValidationMiddlewareTest.php index d4d999fb041f..e0a0387a4180 100644 --- a/src/Symfony/Component/Messenger/Tests/Middleware/ValidationMiddlewareTest.php +++ b/src/Symfony/Component/Messenger/Tests/Middleware/ValidationMiddlewareTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Messenger\Tests\Middleware; use Symfony\Component\Messenger\Envelope; +use Symfony\Component\Messenger\Exception\ValidationFailedException; use Symfony\Component\Messenger\Middleware\ValidationMiddleware; use Symfony\Component\Messenger\Stamp\ValidationStamp; use Symfony\Component\Messenger\Test\Middleware\MiddlewareTestCase; @@ -54,7 +55,7 @@ public function testValidateWithStampAndNextMiddleware() public function testValidationFailedException() { - $this->expectException(\Symfony\Component\Messenger\Exception\ValidationFailedException::class); + $this->expectException(ValidationFailedException::class); $this->expectExceptionMessage('Message of type "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage" failed validation.'); $message = new DummyMessage('Hey'); $envelope = new Envelope($message); diff --git a/src/Symfony/Component/Messenger/Tests/TraceableMessageBusTest.php b/src/Symfony/Component/Messenger/Tests/TraceableMessageBusTest.php index c83ba015a474..d0b7db99e0c9 100644 --- a/src/Symfony/Component/Messenger/Tests/TraceableMessageBusTest.php +++ b/src/Symfony/Component/Messenger/Tests/TraceableMessageBusTest.php @@ -28,7 +28,7 @@ public function testItTracesDispatch() $message = new DummyMessage('Hello'); $stamp = new DelayStamp(5); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $bus->expects($this->once())->method('dispatch')->with($message, [$stamp])->willReturn(new Envelope($message, [$stamp])); $traceableBus = new TraceableMessageBus($bus); @@ -53,7 +53,7 @@ public function testItTracesDispatchWhenHandleTraitIsUsed() { $message = new DummyMessage('Hello'); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $bus->expects($this->once())->method('dispatch')->with($message)->willReturn((new Envelope($message))->with($stamp = new HandledStamp('result', 'handlerName'))); $traceableBus = new TraceableMessageBus($bus); @@ -78,7 +78,7 @@ public function testItTracesDispatchWithEnvelope() $message = new DummyMessage('Hello'); $envelope = (new Envelope($message))->with($stamp = new AnEnvelopeStamp()); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $bus->expects($this->once())->method('dispatch')->with($envelope)->willReturn($envelope); $traceableBus = new TraceableMessageBus($bus); @@ -104,7 +104,7 @@ public function testItCollectsStampsAddedDuringDispatch() $message = new DummyMessage('Hello'); $envelope = (new Envelope($message))->with($stamp = new AnEnvelopeStamp()); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $bus->expects($this->once())->method('dispatch')->with($envelope)->willReturn($envelope->with($anotherStamp = new AnEnvelopeStamp())); $traceableBus = new TraceableMessageBus($bus); @@ -129,7 +129,7 @@ public function testItTracesExceptions() { $message = new DummyMessage('Hello'); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $bus->expects($this->once())->method('dispatch')->with($message)->willThrowException($exception = new \RuntimeException('Meh.')); $traceableBus = new TraceableMessageBus($bus); diff --git a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpReceiverTest.php b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpReceiverTest.php index 8dd8519e4b71..1fb7654a7fb7 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpReceiverTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpReceiverTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Messenger\Envelope; +use Symfony\Component\Messenger\Exception\TransportException; use Symfony\Component\Messenger\Tests\Fixtures\DummyMessage; use Symfony\Component\Messenger\Transport\AmqpExt\AmqpReceivedStamp; use Symfony\Component\Messenger\Transport\AmqpExt\AmqpReceiver; @@ -35,7 +36,7 @@ public function testItReturnsTheDecodedMessageToTheHandler() ); $amqpEnvelope = $this->createAMQPEnvelope(); - $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); + $connection = $this->createMock(Connection::class); $connection->method('getQueueNames')->willReturn(['queueName']); $connection->method('get')->with('queueName')->willReturn($amqpEnvelope); @@ -47,10 +48,10 @@ public function testItReturnsTheDecodedMessageToTheHandler() public function testItThrowsATransportExceptionIfItCannotAcknowledgeMessage() { - $this->expectException(\Symfony\Component\Messenger\Exception\TransportException::class); + $this->expectException(TransportException::class); $serializer = $this->createMock(SerializerInterface::class); $amqpEnvelope = $this->createAMQPEnvelope(); - $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); + $connection = $this->createMock(Connection::class); $connection->method('getQueueNames')->willReturn(['queueName']); $connection->method('get')->with('queueName')->willReturn($amqpEnvelope); $connection->method('ack')->with($amqpEnvelope, 'queueName')->willThrowException(new \AMQPException()); @@ -61,10 +62,10 @@ public function testItThrowsATransportExceptionIfItCannotAcknowledgeMessage() public function testItThrowsATransportExceptionIfItCannotRejectMessage() { - $this->expectException(\Symfony\Component\Messenger\Exception\TransportException::class); + $this->expectException(TransportException::class); $serializer = $this->createMock(SerializerInterface::class); $amqpEnvelope = $this->createAMQPEnvelope(); - $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); + $connection = $this->createMock(Connection::class); $connection->method('getQueueNames')->willReturn(['queueName']); $connection->method('get')->with('queueName')->willReturn($amqpEnvelope); $connection->method('nack')->with($amqpEnvelope, 'queueName', \AMQP_NOPARAM)->willThrowException(new \AMQPException()); @@ -75,7 +76,7 @@ public function testItThrowsATransportExceptionIfItCannotRejectMessage() private function createAMQPEnvelope(): \AMQPEnvelope { - $envelope = $this->getMockBuilder(\AMQPEnvelope::class)->getMock(); + $envelope = $this->createMock(\AMQPEnvelope::class); $envelope->method('getBody')->willReturn('{"message": "Hi"}'); $envelope->method('getHeaders')->willReturn([ 'type' => DummyMessage::class, diff --git a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpSenderTest.php b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpSenderTest.php index 4980811dd0b9..8349d721aec8 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpSenderTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpSenderTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Messenger\Envelope; +use Symfony\Component\Messenger\Exception\TransportException; use Symfony\Component\Messenger\Tests\Fixtures\DummyMessage; use Symfony\Component\Messenger\Transport\AmqpExt\AmqpSender; use Symfony\Component\Messenger\Transport\AmqpExt\AmqpStamp; @@ -29,10 +30,10 @@ public function testItSendsTheEncodedMessage() $envelope = new Envelope(new DummyMessage('Oy')); $encoded = ['body' => '...', 'headers' => ['type' => DummyMessage::class]]; - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer = $this->createMock(SerializerInterface::class); $serializer->method('encode')->with($envelope)->willReturnOnConsecutiveCalls($encoded); - $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); + $connection = $this->createMock(Connection::class); $connection->expects($this->once())->method('publish')->with($encoded['body'], $encoded['headers']); $sender = new AmqpSender($connection, $serializer); @@ -59,10 +60,10 @@ public function testItSendsTheEncodedMessageWithoutHeaders() $envelope = new Envelope(new DummyMessage('Oy')); $encoded = ['body' => '...']; - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer = $this->createMock(SerializerInterface::class); $serializer->method('encode')->with($envelope)->willReturnOnConsecutiveCalls($encoded); - $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); + $connection = $this->createMock(Connection::class); $connection->expects($this->once())->method('publish')->with($encoded['body'], []); $sender = new AmqpSender($connection, $serializer); @@ -74,10 +75,10 @@ public function testContentTypeHeaderIsMovedToAttribute() $envelope = new Envelope(new DummyMessage('Oy')); $encoded = ['body' => '...', 'headers' => ['type' => DummyMessage::class, 'Content-Type' => 'application/json']]; - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer = $this->createMock(SerializerInterface::class); $serializer->method('encode')->with($envelope)->willReturnOnConsecutiveCalls($encoded); - $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); + $connection = $this->createMock(Connection::class); unset($encoded['headers']['Content-Type']); $stamp = new AmqpStamp(null, \AMQP_NOPARAM, ['content_type' => 'application/json']); $connection->expects($this->once())->method('publish')->with($encoded['body'], $encoded['headers'], 0, $stamp); @@ -91,10 +92,10 @@ public function testContentTypeHeaderDoesNotOverwriteAttribute() $envelope = (new Envelope(new DummyMessage('Oy')))->with($stamp = new AmqpStamp('rk', \AMQP_NOPARAM, ['content_type' => 'custom'])); $encoded = ['body' => '...', 'headers' => ['type' => DummyMessage::class, 'Content-Type' => 'application/json']]; - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer = $this->createMock(SerializerInterface::class); $serializer->method('encode')->with($envelope)->willReturnOnConsecutiveCalls($encoded); - $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); + $connection = $this->createMock(Connection::class); unset($encoded['headers']['Content-Type']); $connection->expects($this->once())->method('publish')->with($encoded['body'], $encoded['headers'], 0, $stamp); @@ -104,14 +105,14 @@ public function testContentTypeHeaderDoesNotOverwriteAttribute() public function testItThrowsATransportExceptionIfItCannotSendTheMessage() { - $this->expectException(\Symfony\Component\Messenger\Exception\TransportException::class); + $this->expectException(TransportException::class); $envelope = new Envelope(new DummyMessage('Oy')); $encoded = ['body' => '...', 'headers' => ['type' => DummyMessage::class]]; - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer = $this->createMock(SerializerInterface::class); $serializer->method('encode')->with($envelope)->willReturnOnConsecutiveCalls($encoded); - $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); + $connection = $this->createMock(Connection::class); $connection->method('publish')->with($encoded['body'], $encoded['headers'])->willThrowException(new \AMQPException()); $sender = new AmqpSender($connection, $serializer); diff --git a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpTransportTest.php b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpTransportTest.php index 6618d2fc76c1..0a7540e4b25b 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpTransportTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpTransportTest.php @@ -34,13 +34,13 @@ public function testItIsATransport() public function testReceivesMessages() { $transport = $this->getTransport( - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(), - $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock() + $serializer = $this->createMock(SerializerInterface::class), + $connection = $this->createMock(Connection::class) ); $decodedMessage = new DummyMessage('Decoded.'); - $amqpEnvelope = $this->getMockBuilder(\AMQPEnvelope::class)->getMock(); + $amqpEnvelope = $this->createMock(\AMQPEnvelope::class); $amqpEnvelope->method('getBody')->willReturn('body'); $amqpEnvelope->method('getHeaders')->willReturn(['my' => 'header']); @@ -54,8 +54,8 @@ public function testReceivesMessages() private function getTransport(SerializerInterface $serializer = null, Connection $connection = null): AmqpTransport { - $serializer = $serializer ?: $this->getMockBuilder(SerializerInterface::class)->getMock(); - $connection = $connection ?: $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); + $serializer = $serializer ?: $this->createMock(SerializerInterface::class); + $connection = $connection ?: $this->createMock(Connection::class); return new AmqpTransport($connection, $serializer); } diff --git a/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/ConnectionTest.php b/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/ConnectionTest.php index c2c7cf69a9ea..9ad839942648 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/ConnectionTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/ConnectionTest.php @@ -26,6 +26,8 @@ use Doctrine\DBAL\Schema\SchemaConfig; use Doctrine\DBAL\Statement; use PHPUnit\Framework\TestCase; +use Symfony\Component\Messenger\Exception\InvalidArgumentException; +use Symfony\Component\Messenger\Exception\TransportException; use Symfony\Component\Messenger\Tests\Fixtures\DummyMessage; use Symfony\Component\Messenger\Transport\Doctrine\Connection; @@ -92,7 +94,7 @@ public function testGetWithNoPendingMessageWillReturnNull() public function testItThrowsATransportExceptionIfItCannotAcknowledgeMessage() { - $this->expectException(\Symfony\Component\Messenger\Exception\TransportException::class); + $this->expectException(TransportException::class); $driverConnection = $this->getDBALConnectionMock(); if (class_exists(Exception::class)) { @@ -107,7 +109,7 @@ public function testItThrowsATransportExceptionIfItCannotAcknowledgeMessage() public function testItThrowsATransportExceptionIfItCannotRejectMessage() { - $this->expectException(\Symfony\Component\Messenger\Exception\TransportException::class); + $this->expectException(TransportException::class); $driverConnection = $this->getDBALConnectionMock(); if (class_exists(Exception::class)) { @@ -256,13 +258,13 @@ public function buildConfigurationProvider(): iterable public function testItThrowsAnExceptionIfAnExtraOptionsInDefined() { - $this->expectException(\Symfony\Component\Messenger\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); Connection::buildConfiguration('doctrine://default', ['new_option' => 'woops']); } public function testItThrowsAnExceptionIfAnExtraOptionsInDefinedInDSN() { - $this->expectException(\Symfony\Component\Messenger\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); Connection::buildConfiguration('doctrine://default?new_option=woops'); } diff --git a/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/DoctrineTransportFactoryTest.php b/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/DoctrineTransportFactoryTest.php index 74564531b807..a7c857bbc02c 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/DoctrineTransportFactoryTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/DoctrineTransportFactoryTest.php @@ -15,6 +15,7 @@ use Doctrine\DBAL\Schema\SchemaConfig; use Doctrine\Persistence\ConnectionRegistry; use PHPUnit\Framework\TestCase; +use Symfony\Component\Messenger\Exception\TransportException; use Symfony\Component\Messenger\Transport\Doctrine\Connection; use Symfony\Component\Messenger\Transport\Doctrine\DoctrineTransport; use Symfony\Component\Messenger\Transport\Doctrine\DoctrineTransportFactory; @@ -56,7 +57,7 @@ public function testCreateTransport() public function testCreateTransportMustThrowAnExceptionIfManagerIsNotFound() { - $this->expectException(\Symfony\Component\Messenger\Exception\TransportException::class); + $this->expectException(TransportException::class); $this->expectExceptionMessage('Could not find Doctrine connection from Messenger DSN "doctrine://default".'); $registry = $this->createMock(ConnectionRegistry::class); $registry->expects($this->once()) diff --git a/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/ConnectionTest.php b/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/ConnectionTest.php index 66a53f790f50..26a79b58b771 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/ConnectionTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/ConnectionTest.php @@ -100,7 +100,7 @@ public function testFromDsnWithMixDsnQueryOptions() public function testKeepGettingPendingMessages() { - $redis = $this->getMockBuilder(\Redis::class)->disableOriginalConstructor()->getMock(); + $redis = $this->createMock(\Redis::class); $redis->expects($this->exactly(3))->method('xreadgroup') ->with('symfony', 'consumer', ['queue' => 0], 1, null) @@ -114,7 +114,7 @@ public function testKeepGettingPendingMessages() public function testAuth() { - $redis = $this->getMockBuilder(\Redis::class)->disableOriginalConstructor()->getMock(); + $redis = $this->createMock(\Redis::class); $redis->expects($this->exactly(1))->method('auth') ->with('password') @@ -125,7 +125,7 @@ public function testAuth() public function testNoAuthWithEmptyPassword() { - $redis = $this->getMockBuilder(\Redis::class)->disableOriginalConstructor()->getMock(); + $redis = $this->createMock(\Redis::class); $redis->expects($this->exactly(0))->method('auth') ->with('') @@ -136,7 +136,7 @@ public function testNoAuthWithEmptyPassword() public function testAuthZeroPassword() { - $redis = $this->getMockBuilder(\Redis::class)->disableOriginalConstructor()->getMock(); + $redis = $this->createMock(\Redis::class); $redis->expects($this->exactly(1))->method('auth') ->with('0') @@ -149,7 +149,7 @@ public function testFailedAuth() { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Redis connection '); - $redis = $this->getMockBuilder(\Redis::class)->disableOriginalConstructor()->getMock(); + $redis = $this->createMock(\Redis::class); $redis->expects($this->exactly(1))->method('auth') ->with('password') @@ -169,7 +169,7 @@ public function testDbIndex() public function testFirstGetPendingMessagesThenNewMessages() { - $redis = $this->getMockBuilder(\Redis::class)->disableOriginalConstructor()->getMock(); + $redis = $this->createMock(\Redis::class); $count = 0; @@ -193,7 +193,7 @@ public function testUnexpectedRedisError() { $this->expectException(TransportException::class); $this->expectExceptionMessage('Redis error happens'); - $redis = $this->getMockBuilder(\Redis::class)->disableOriginalConstructor()->getMock(); + $redis = $this->createMock(\Redis::class); $redis->expects($this->once())->method('xreadgroup')->willReturn(false); $redis->expects($this->once())->method('getLastError')->willReturn('Redis error happens'); @@ -245,7 +245,7 @@ public function testJsonError() public function testMaxEntries() { - $redis = $this->getMockBuilder(\Redis::class)->disableOriginalConstructor()->getMock(); + $redis = $this->createMock(\Redis::class); $redis->expects($this->exactly(1))->method('xadd') ->with('queue', '*', ['message' => '{"body":"1","headers":[]}'], 20000, true) @@ -257,7 +257,7 @@ public function testMaxEntries() public function testLastErrorGetsCleared() { - $redis = $this->getMockBuilder(\Redis::class)->disableOriginalConstructor()->getMock(); + $redis = $this->createMock(\Redis::class); $redis->expects($this->once())->method('xadd')->willReturn(0); $redis->expects($this->once())->method('xack')->willReturn(0); diff --git a/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisReceiverTest.php b/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisReceiverTest.php index 0da0e78ff8e8..0f7373a97ad8 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisReceiverTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisReceiverTest.php @@ -29,7 +29,7 @@ public function testItReturnsTheDecodedMessageToTheHandler() $serializer = $this->createSerializer(); $redisEnvelop = $this->createRedisEnvelope(); - $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); + $connection = $this->createMock(Connection::class); $connection->method('get')->willReturn($redisEnvelop); $receiver = new RedisReceiver($connection, $serializer); @@ -46,7 +46,7 @@ public function testItRejectTheMessageIfThereIsAMessageDecodingFailedException() $serializer->method('decode')->willThrowException(new MessageDecodingFailedException()); $redisEnvelop = $this->createRedisEnvelope(); - $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); + $connection = $this->createMock(Connection::class); $connection->method('get')->willReturn($redisEnvelop); $connection->expects($this->once())->method('reject'); diff --git a/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisSenderTest.php b/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisSenderTest.php index 5cbda34e10b9..52aaafe4bf0f 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisSenderTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisSenderTest.php @@ -25,12 +25,10 @@ public function testSend() $envelope = new Envelope(new DummyMessage('Oy')); $encoded = ['body' => '...', 'headers' => ['type' => DummyMessage::class]]; - $connection = $this->getMockBuilder(Connection::class) - ->disableOriginalConstructor() - ->getMock(); + $connection = $this->createMock(Connection::class); $connection->expects($this->once())->method('add')->with($encoded['body'], $encoded['headers']); - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer = $this->createMock(SerializerInterface::class); $serializer->method('encode')->with($envelope)->willReturnOnConsecutiveCalls($encoded); $sender = new RedisSender($connection, $serializer); diff --git a/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisTransportFactoryTest.php b/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisTransportFactoryTest.php index 945b7d130f5b..7e02c0d46acb 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisTransportFactoryTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisTransportFactoryTest.php @@ -39,7 +39,7 @@ public function testCreateTransport() $this->skipIfRedisUnavailable(); $factory = new RedisTransportFactory(); - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer = $this->createMock(SerializerInterface::class); $expectedTransport = new RedisTransport(Connection::fromDsn('redis://'.getenv('REDIS_HOST'), ['foo' => 'bar']), $serializer); $this->assertEquals($expectedTransport, $factory->createTransport('redis://'.getenv('REDIS_HOST'), ['foo' => 'bar'], $serializer)); diff --git a/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisTransportTest.php b/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisTransportTest.php index 8ca97243ae2e..e40994663f4a 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisTransportTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisTransportTest.php @@ -31,8 +31,8 @@ public function testItIsATransport() public function testReceivesMessages() { $transport = $this->getTransport( - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(), - $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock() + $serializer = $this->createMock(SerializerInterface::class), + $connection = $this->createMock(Connection::class) ); $decodedMessage = new DummyMessage('Decoded.'); @@ -52,8 +52,8 @@ public function testReceivesMessages() private function getTransport(SerializerInterface $serializer = null, Connection $connection = null): RedisTransport { - $serializer = $serializer ?: $this->getMockBuilder(SerializerInterface::class)->getMock(); - $connection = $connection ?: $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); + $serializer = $serializer ?: $this->createMock(SerializerInterface::class); + $connection = $connection ?: $this->createMock(Connection::class); return new RedisTransport($connection, $serializer); } diff --git a/src/Symfony/Component/Messenger/Tests/Transport/Sender/SendersLocatorTest.php b/src/Symfony/Component/Messenger/Tests/Transport/Sender/SendersLocatorTest.php index b5c87e58da32..10c697e4f024 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/Sender/SendersLocatorTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/Sender/SendersLocatorTest.php @@ -23,7 +23,7 @@ class SendersLocatorTest extends TestCase { public function testItReturnsTheSenderBasedOnTheMessageClass() { - $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); + $sender = $this->createMock(SenderInterface::class); $sendersLocator = $this->createContainer([ 'my_sender' => $sender, ]); @@ -40,7 +40,7 @@ public function testItReturnsTheSenderBasedOnTheMessageClass() */ public function testItReturnsTheSenderBasedOnTheMessageClassLegacy() { - $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); + $sender = $this->createMock(SenderInterface::class); $locator = new SendersLocator([ DummyMessage::class => [$sender], ]); @@ -53,7 +53,7 @@ public function testItReturnsTheSenderBasedOnTheMessageClassLegacy() */ public function testItYieldsProvidedSenderAliasAsKeyLegacy() { - $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); + $sender = $this->createMock(SenderInterface::class); $locator = new SendersLocator([ DummyMessage::class => ['dummy' => $sender], ]); diff --git a/src/Symfony/Component/Messenger/Tests/Transport/Serialization/SerializerTest.php b/src/Symfony/Component/Messenger/Tests/Transport/Serialization/SerializerTest.php index adff357dc91b..eff4d8614f10 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/Serialization/SerializerTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/Serialization/SerializerTest.php @@ -63,7 +63,7 @@ public function testUsesTheCustomFormatAndContext() { $message = new DummyMessage('Foo'); - $serializer = $this->getMockBuilder(SerializerComponent\SerializerInterface::class)->getMock(); + $serializer = $this->createMock(SerializerComponent\SerializerInterface::class); $serializer->expects($this->once())->method('serialize')->with($message, 'csv', ['foo' => 'bar'])->willReturn('Yay'); $serializer->expects($this->once())->method('deserialize')->with('Yay', DummyMessage::class, 'csv', ['foo' => 'bar'])->willReturn($message); diff --git a/src/Symfony/Component/Messenger/Tests/WorkerTest.php b/src/Symfony/Component/Messenger/Tests/WorkerTest.php index 28349d804ced..85f9db781be6 100644 --- a/src/Symfony/Component/Messenger/Tests/WorkerTest.php +++ b/src/Symfony/Component/Messenger/Tests/WorkerTest.php @@ -44,7 +44,7 @@ public function testWorkerDispatchTheReceivedMessage() [new Envelope($apiMessage), new Envelope($ipaMessage)], ]); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $bus->expects($this->exactly(2)) ->method('dispatch') @@ -72,7 +72,7 @@ public function testHandlingErrorCausesReject() [new Envelope(new DummyMessage('Hello'), [new SentStamp('Some\Sender', 'transport1')])], ]); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $bus->method('dispatch')->willThrowException(new \InvalidArgumentException('Why not')); $dispatcher = new EventDispatcher(); @@ -91,7 +91,7 @@ public function testWorkerDoesNotSendNullMessagesToTheBus() null, ]); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $bus->expects($this->never())->method('dispatch'); $dispatcher = new EventDispatcher(); @@ -108,10 +108,10 @@ public function testWorkerDispatchesEventsOnSuccess() $envelope = new Envelope(new DummyMessage('Hello')); $receiver = new DummyReceiver([[$envelope]]); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $bus->method('dispatch')->willReturn($envelope); - $eventDispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); + $eventDispatcher = $this->createMock(EventDispatcherInterface::class); $eventDispatcher->expects($this->exactly(5)) ->method('dispatch') @@ -138,11 +138,11 @@ public function testWorkerDispatchesEventsOnError() $envelope = new Envelope(new DummyMessage('Hello')); $receiver = new DummyReceiver([[$envelope]]); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $exception = new \InvalidArgumentException('Oh no!'); $bus->method('dispatch')->willThrowException($exception); - $eventDispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); + $eventDispatcher = $this->createMock(EventDispatcherInterface::class); $eventDispatcher->expects($this->exactly(5)) ->method('dispatch') @@ -177,7 +177,7 @@ public function testTimeoutIsConfigurable() [new Envelope($apiMessage)], ]); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $dispatcher = new EventDispatcher(); $dispatcher->addSubscriber(new StopWorkerOnMessageLimitListener(5)); @@ -229,7 +229,7 @@ public function testWorkerWithMultipleReceivers() [$envelope6], ]); - $bus = $this->getMockBuilder(MessageBusInterface::class)->getMock(); + $bus = $this->createMock(MessageBusInterface::class); $processedEnvelopes = []; $dispatcher = new EventDispatcher(); diff --git a/src/Symfony/Component/Mime/Tests/Header/MailboxHeaderTest.php b/src/Symfony/Component/Mime/Tests/Header/MailboxHeaderTest.php index 803afc489d06..4d9bf5268530 100644 --- a/src/Symfony/Component/Mime/Tests/Header/MailboxHeaderTest.php +++ b/src/Symfony/Component/Mime/Tests/Header/MailboxHeaderTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Mime\Address; +use Symfony\Component\Mime\Exception\AddressEncoderException; use Symfony\Component\Mime\Header\MailboxHeader; class MailboxHeaderTest extends TestCase @@ -60,7 +61,7 @@ public function testgetBodyAsString() public function testUtf8CharsInLocalPartThrows() { - $this->expectException(\Symfony\Component\Mime\Exception\AddressEncoderException::class); + $this->expectException(AddressEncoderException::class); $header = new MailboxHeader('Sender', new Address('fabïen@symfony.com')); $header->getBodyAsString(); } diff --git a/src/Symfony/Component/Mime/Tests/Header/MailboxListHeaderTest.php b/src/Symfony/Component/Mime/Tests/Header/MailboxListHeaderTest.php index c842fa170826..1c047cd2b184 100644 --- a/src/Symfony/Component/Mime/Tests/Header/MailboxListHeaderTest.php +++ b/src/Symfony/Component/Mime/Tests/Header/MailboxListHeaderTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Mime\Address; +use Symfony\Component\Mime\Exception\AddressEncoderException; use Symfony\Component\Mime\Header\MailboxListHeader; class MailboxListHeaderTest extends TestCase @@ -57,7 +58,7 @@ public function testUtf8CharsInDomainAreIdnEncoded() public function testUtf8CharsInLocalPartThrows() { - $this->expectException(\Symfony\Component\Mime\Exception\AddressEncoderException::class); + $this->expectException(AddressEncoderException::class); $header = new MailboxListHeader('From', [new Address('chrïs@swiftmailer.org', 'Chris Corbyn')]); $header->getAddressStrings(); } diff --git a/src/Symfony/Component/Mime/Tests/Header/PathHeaderTest.php b/src/Symfony/Component/Mime/Tests/Header/PathHeaderTest.php index fe006f2d890f..c129e954f352 100644 --- a/src/Symfony/Component/Mime/Tests/Header/PathHeaderTest.php +++ b/src/Symfony/Component/Mime/Tests/Header/PathHeaderTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Mime\Address; +use Symfony\Component\Mime\Exception\AddressEncoderException; use Symfony\Component\Mime\Header\PathHeader; class PathHeaderTest extends TestCase @@ -51,7 +52,7 @@ public function testAddressIsIdnEncoded() public function testAddressMustBeEncodable() { - $this->expectException(\Symfony\Component\Mime\Exception\AddressEncoderException::class); + $this->expectException(AddressEncoderException::class); $header = new PathHeader('Return-Path', new Address('chrïs@swiftmailer.org')); $header->getBodyAsString(); } diff --git a/src/Symfony/Component/OptionsResolver/Tests/Debug/OptionsResolverIntrospectorTest.php b/src/Symfony/Component/OptionsResolver/Tests/Debug/OptionsResolverIntrospectorTest.php index b18225cc6743..f66e0813fed2 100644 --- a/src/Symfony/Component/OptionsResolver/Tests/Debug/OptionsResolverIntrospectorTest.php +++ b/src/Symfony/Component/OptionsResolver/Tests/Debug/OptionsResolverIntrospectorTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\OptionsResolver\Debug\OptionsResolverIntrospector; +use Symfony\Component\OptionsResolver\Exception\NoConfigurationException; +use Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -38,7 +40,7 @@ public function testGetDefaultNull() public function testGetDefaultThrowsOnNoConfiguredValue() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\NoConfigurationException::class); + $this->expectException(NoConfigurationException::class); $this->expectExceptionMessage('No default value was set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined($option = 'foo'); @@ -49,7 +51,7 @@ public function testGetDefaultThrowsOnNoConfiguredValue() public function testGetDefaultThrowsOnNotDefinedOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); @@ -69,7 +71,7 @@ public function testGetLazyClosures() public function testGetLazyClosuresThrowsOnNoConfiguredValue() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\NoConfigurationException::class); + $this->expectException(NoConfigurationException::class); $this->expectExceptionMessage('No lazy closures were set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined($option = 'foo'); @@ -80,7 +82,7 @@ public function testGetLazyClosuresThrowsOnNoConfiguredValue() public function testGetLazyClosuresThrowsOnNotDefinedOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); @@ -100,7 +102,7 @@ public function testGetAllowedTypes() public function testGetAllowedTypesThrowsOnNoConfiguredValue() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\NoConfigurationException::class); + $this->expectException(NoConfigurationException::class); $this->expectExceptionMessage('No allowed types were set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined($option = 'foo'); @@ -111,7 +113,7 @@ public function testGetAllowedTypesThrowsOnNoConfiguredValue() public function testGetAllowedTypesThrowsOnNotDefinedOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); @@ -131,7 +133,7 @@ public function testGetAllowedValues() public function testGetAllowedValuesThrowsOnNoConfiguredValue() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\NoConfigurationException::class); + $this->expectException(NoConfigurationException::class); $this->expectExceptionMessage('No allowed values were set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined($option = 'foo'); @@ -142,7 +144,7 @@ public function testGetAllowedValuesThrowsOnNoConfiguredValue() public function testGetAllowedValuesThrowsOnNotDefinedOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); @@ -162,7 +164,7 @@ public function testGetNormalizer() public function testGetNormalizerThrowsOnNoConfiguredValue() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\NoConfigurationException::class); + $this->expectException(NoConfigurationException::class); $this->expectExceptionMessage('No normalizer was set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined($option = 'foo'); @@ -173,7 +175,7 @@ public function testGetNormalizerThrowsOnNoConfiguredValue() public function testGetNormalizerThrowsOnNotDefinedOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); @@ -194,7 +196,7 @@ public function testGetNormalizers() public function testGetNormalizersThrowsOnNoConfiguredValue() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\NoConfigurationException::class); + $this->expectException(NoConfigurationException::class); $this->expectExceptionMessage('No normalizer was set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined('foo'); @@ -205,7 +207,7 @@ public function testGetNormalizersThrowsOnNoConfiguredValue() public function testGetNormalizersThrowsOnNotDefinedOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); @@ -235,7 +237,7 @@ public function testGetClosureDeprecationMessage() public function testGetDeprecationMessageThrowsOnNoConfiguredValue() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\NoConfigurationException::class); + $this->expectException(NoConfigurationException::class); $this->expectExceptionMessage('No deprecation was set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined('foo'); @@ -246,7 +248,7 @@ public function testGetDeprecationMessageThrowsOnNoConfiguredValue() public function testGetDeprecationMessageThrowsOnNotDefinedOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); diff --git a/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php b/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php index 4219771d6048..b3de4ae5d54c 100644 --- a/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php +++ b/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php @@ -13,7 +13,13 @@ use PHPUnit\Framework\Assert; use PHPUnit\Framework\TestCase; +use Symfony\Component\OptionsResolver\Exception\AccessException; +use Symfony\Component\OptionsResolver\Exception\InvalidArgumentException; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\Exception\MissingOptionsException; +use Symfony\Component\OptionsResolver\Exception\NoSuchOptionException; +use Symfony\Component\OptionsResolver\Exception\OptionDefinitionException; +use Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -31,7 +37,7 @@ protected function setUp(): void public function testResolveFailsIfNonExistingOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->expectExceptionMessage('The option "foo" does not exist. Defined options are: "a", "z".'); $this->resolver->setDefault('z', '1'); $this->resolver->setDefault('a', '2'); @@ -41,7 +47,7 @@ public function testResolveFailsIfNonExistingOption() public function testResolveFailsIfMultipleNonExistingOptions() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->expectExceptionMessage('The options "baz", "foo", "ping" do not exist. Defined options are: "a", "z".'); $this->resolver->setDefault('z', '1'); $this->resolver->setDefault('a', '2'); @@ -51,7 +57,7 @@ public function testResolveFailsIfMultipleNonExistingOptions() public function testResolveFailsFromLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('foo', function (Options $options) { $options->resolve([]); }); @@ -77,7 +83,7 @@ public function testSetDefault() public function testFailIfSetDefaultFromLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('lazy', function (Options $options) { $options->setDefault('default', 42); }); @@ -219,7 +225,7 @@ public function testSetRequiredReturnsThis() public function testFailIfSetRequiredFromLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('foo', function (Options $options) { $options->setRequired('bar'); }); @@ -229,7 +235,7 @@ public function testFailIfSetRequiredFromLazyOption() public function testResolveFailsIfRequiredOptionMissing() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\MissingOptionsException::class); + $this->expectException(MissingOptionsException::class); $this->resolver->setRequired('foo'); $this->resolver->resolve(); @@ -343,7 +349,7 @@ public function testGetMissingOptions() public function testFailIfSetDefinedFromLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('foo', function (Options $options) { $options->setDefined('bar'); }); @@ -438,7 +444,7 @@ public function testClearedOptionsAreNotDefined() public function testFailIfSetDeprecatedFromLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver ->setDefault('bar', 'baz') ->setDefault('foo', function (Options $options) { @@ -450,13 +456,13 @@ public function testFailIfSetDeprecatedFromLazyOption() public function testSetDeprecatedFailsIfUnknownOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->resolver->setDeprecated('foo'); } public function testSetDeprecatedFailsIfInvalidDeprecationMessageType() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid type for deprecation message argument, expected string or \Closure, but got "boolean".'); $this->resolver ->setDefined('foo') @@ -466,7 +472,7 @@ public function testSetDeprecatedFailsIfInvalidDeprecationMessageType() public function testLazyDeprecationFailsIfInvalidDeprecationMessageType() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid type for deprecation message, expected string but got "boolean", return an empty string to ignore.'); $this->resolver ->setDefined('foo') @@ -479,7 +485,7 @@ public function testLazyDeprecationFailsIfInvalidDeprecationMessageType() public function testFailsIfCyclicDependencyBetweenDeprecation() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\OptionDefinitionException::class); + $this->expectException(OptionDefinitionException::class); $this->expectExceptionMessage('The options "foo", "bar" have a cyclic dependency.'); $this->resolver ->setDefined(['foo', 'bar']) @@ -750,7 +756,7 @@ function (OptionsResolver $resolver) { public function testSetAllowedTypesFailsIfUnknownOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->resolver->setAllowedTypes('foo', 'string'); } @@ -765,7 +771,7 @@ public function testResolveTypedArray() public function testFailIfSetAllowedTypesFromLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('foo', function (Options $options) { $options->setAllowedTypes('bar', 'string'); }); @@ -917,13 +923,13 @@ public function testResolveFailsIfNotInstanceOfClass() public function testAddAllowedTypesFailsIfUnknownOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->resolver->addAllowedTypes('foo', 'string'); } public function testFailIfAddAllowedTypesFromLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('foo', function (Options $options) { $options->addAllowedTypes('bar', 'string'); }); @@ -991,13 +997,13 @@ public function testAddAllowedTypesDoesNotOverwrite2() public function testSetAllowedValuesFailsIfUnknownOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->resolver->setAllowedValues('foo', 'bar'); } public function testFailIfSetAllowedValuesFromLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('foo', function (Options $options) { $options->setAllowedValues('bar', 'baz'); }); @@ -1128,13 +1134,13 @@ function () { return false; }, public function testAddAllowedValuesFailsIfUnknownOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->resolver->addAllowedValues('foo', 'bar'); } public function testFailIfAddAllowedValuesFromLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('foo', function (Options $options) { $options->addAllowedValues('bar', 'baz'); }); @@ -1250,13 +1256,13 @@ public function testSetNormalizerClosure() public function testSetNormalizerFailsIfUnknownOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->resolver->setNormalizer('foo', function () {}); } public function testFailIfSetNormalizerFromLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('foo', function (Options $options) { $options->setNormalizer('foo', function () {}); }); @@ -1358,7 +1364,7 @@ public function testNormalizerCanAccessLazyOptions() public function testFailIfCyclicDependencyBetweenNormalizers() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\OptionDefinitionException::class); + $this->expectException(OptionDefinitionException::class); $this->resolver->setDefault('norm1', 'bar'); $this->resolver->setDefault('norm2', 'baz'); @@ -1375,7 +1381,7 @@ public function testFailIfCyclicDependencyBetweenNormalizers() public function testFailIfCyclicDependencyBetweenNormalizerAndLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\OptionDefinitionException::class); + $this->expectException(OptionDefinitionException::class); $this->resolver->setDefault('lazy', function (Options $options) { $options['norm']; }); @@ -1521,13 +1527,13 @@ public function testForcePrependNormalizerForResolverWithoutPreviousNormalizers( public function testAddNormalizerFailsIfUnknownOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->resolver->addNormalizer('foo', function () {}); } public function testFailIfAddNormalizerFromLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('foo', function (Options $options) { $options->addNormalizer('foo', function () {}); }); @@ -1559,7 +1565,7 @@ public function testSetDefaults() public function testFailIfSetDefaultsFromLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('foo', function (Options $options) { $options->setDefaults(['two' => '2']); }); @@ -1638,7 +1644,7 @@ public function testRemoveAllowedValues() public function testFailIfRemoveFromLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('foo', function (Options $options) { $options->remove('bar'); }); @@ -1712,7 +1718,7 @@ public function testClearAllowedValues() public function testFailIfClearFromLazyption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('foo', function (Options $options) { $options->clear(); }); @@ -1769,7 +1775,7 @@ public function testArrayAccess() public function testArrayAccessGetFailsOutsideResolve() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('default', 0); $this->resolver['default']; @@ -1777,7 +1783,7 @@ public function testArrayAccessGetFailsOutsideResolve() public function testArrayAccessExistsFailsOutsideResolve() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('default', 0); isset($this->resolver['default']); @@ -1785,13 +1791,13 @@ public function testArrayAccessExistsFailsOutsideResolve() public function testArrayAccessSetNotSupported() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver['default'] = 0; } public function testArrayAccessUnsetNotSupported() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('default', 0); unset($this->resolver['default']); @@ -1799,7 +1805,7 @@ public function testArrayAccessUnsetNotSupported() public function testFailIfGetNonExisting() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\NoSuchOptionException::class); + $this->expectException(NoSuchOptionException::class); $this->expectExceptionMessage('The option "undefined" does not exist. Defined options are: "foo", "lazy".'); $this->resolver->setDefault('foo', 'bar'); @@ -1812,7 +1818,7 @@ public function testFailIfGetNonExisting() public function testFailIfGetDefinedButUnset() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\NoSuchOptionException::class); + $this->expectException(NoSuchOptionException::class); $this->expectExceptionMessage('The optional option "defined" has no value set. You should make sure it is set with "isset" before reading it.'); $this->resolver->setDefined('defined'); @@ -1825,7 +1831,7 @@ public function testFailIfGetDefinedButUnset() public function testFailIfCyclicDependency() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\OptionDefinitionException::class); + $this->expectException(OptionDefinitionException::class); $this->resolver->setDefault('lazy1', function (Options $options) { $options['lazy2']; }); @@ -1858,7 +1864,7 @@ public function testCount() */ public function testCountFailsOutsideResolve() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->resolver->setDefault('foo', 0); $this->resolver->setRequired('bar'); $this->resolver->setDefined('bar'); @@ -2010,7 +2016,7 @@ public function testIsNestedOption() public function testFailsIfUndefinedNestedOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException::class); + $this->expectException(UndefinedOptionsException::class); $this->expectExceptionMessage('The option "database[foo]" does not exist. Defined options are: "host", "port".'); $this->resolver->setDefaults([ 'name' => 'default', @@ -2025,7 +2031,7 @@ public function testFailsIfUndefinedNestedOption() public function testFailsIfMissingRequiredNestedOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\MissingOptionsException::class); + $this->expectException(MissingOptionsException::class); $this->expectExceptionMessage('The required option "database[host]" is missing.'); $this->resolver->setDefaults([ 'name' => 'default', @@ -2264,7 +2270,7 @@ public function testNormalizeNestedValue() public function testFailsIfCyclicDependencyBetweenSameNestedOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\OptionDefinitionException::class); + $this->expectException(OptionDefinitionException::class); $this->resolver->setDefault('database', function (OptionsResolver $resolver, Options $parent) { $resolver->setDefault('replicas', $parent['database']); }); @@ -2273,7 +2279,7 @@ public function testFailsIfCyclicDependencyBetweenSameNestedOption() public function testFailsIfCyclicDependencyBetweenNestedOptionAndParentLazyOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\OptionDefinitionException::class); + $this->expectException(OptionDefinitionException::class); $this->resolver->setDefaults([ 'version' => function (Options $options) { return $options['database']['server_version']; @@ -2287,7 +2293,7 @@ public function testFailsIfCyclicDependencyBetweenNestedOptionAndParentLazyOptio public function testFailsIfCyclicDependencyBetweenNormalizerAndNestedOption() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\OptionDefinitionException::class); + $this->expectException(OptionDefinitionException::class); $this->resolver ->setDefault('name', 'default') ->setDefault('database', function (OptionsResolver $resolver, Options $parent) { @@ -2301,7 +2307,7 @@ public function testFailsIfCyclicDependencyBetweenNormalizerAndNestedOption() public function testFailsIfCyclicDependencyBetweenNestedOptions() { - $this->expectException(\Symfony\Component\OptionsResolver\Exception\OptionDefinitionException::class); + $this->expectException(OptionDefinitionException::class); $this->resolver->setDefault('database', function (OptionsResolver $resolver, Options $parent) { $resolver->setDefault('host', $parent['replica']['host']); }); diff --git a/src/Symfony/Component/Process/Tests/ProcessFailedExceptionTest.php b/src/Symfony/Component/Process/Tests/ProcessFailedExceptionTest.php index 4a0812c7953a..d6d7bfb07e66 100644 --- a/src/Symfony/Component/Process/Tests/ProcessFailedExceptionTest.php +++ b/src/Symfony/Component/Process/Tests/ProcessFailedExceptionTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Process\Exception\ProcessFailedException; +use Symfony\Component\Process\Process; /** * @author Sebastian Marek @@ -24,7 +25,7 @@ class ProcessFailedExceptionTest extends TestCase */ public function testProcessFailedExceptionThrowsException() { - $process = $this->getMockBuilder(\Symfony\Component\Process\Process::class)->setMethods(['isSuccessful'])->setConstructorArgs([['php']])->getMock(); + $process = $this->getMockBuilder(Process::class)->setMethods(['isSuccessful'])->setConstructorArgs([['php']])->getMock(); $process->expects($this->once()) ->method('isSuccessful') ->willReturn(true); @@ -48,7 +49,7 @@ public function testProcessFailedExceptionPopulatesInformationFromProcessOutput( $errorOutput = 'FATAL: Unexpected error'; $workingDirectory = getcwd(); - $process = $this->getMockBuilder(\Symfony\Component\Process\Process::class)->setMethods(['isSuccessful', 'getOutput', 'getErrorOutput', 'getExitCode', 'getExitCodeText', 'isOutputDisabled', 'getWorkingDirectory'])->setConstructorArgs([[$cmd]])->getMock(); + $process = $this->getMockBuilder(Process::class)->setMethods(['isSuccessful', 'getOutput', 'getErrorOutput', 'getExitCode', 'getExitCodeText', 'isOutputDisabled', 'getWorkingDirectory'])->setConstructorArgs([[$cmd]])->getMock(); $process->expects($this->once()) ->method('isSuccessful') ->willReturn(false); @@ -96,7 +97,7 @@ public function testDisabledOutputInFailedExceptionDoesNotPopulateOutput() $exitText = 'General error'; $workingDirectory = getcwd(); - $process = $this->getMockBuilder(\Symfony\Component\Process\Process::class)->setMethods(['isSuccessful', 'isOutputDisabled', 'getExitCode', 'getExitCodeText', 'getOutput', 'getErrorOutput', 'getWorkingDirectory'])->setConstructorArgs([[$cmd]])->getMock(); + $process = $this->getMockBuilder(Process::class)->setMethods(['isSuccessful', 'isOutputDisabled', 'getExitCode', 'getExitCodeText', 'getOutput', 'getErrorOutput', 'getWorkingDirectory'])->setConstructorArgs([[$cmd]])->getMock(); $process->expects($this->once()) ->method('isSuccessful') ->willReturn(false); diff --git a/src/Symfony/Component/Process/Tests/ProcessTest.php b/src/Symfony/Component/Process/Tests/ProcessTest.php index 4fd0df2018ea..7338e4e46342 100644 --- a/src/Symfony/Component/Process/Tests/ProcessTest.php +++ b/src/Symfony/Component/Process/Tests/ProcessTest.php @@ -12,7 +12,10 @@ namespace Symfony\Component\Process\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Process\Exception\InvalidArgumentException; use Symfony\Component\Process\Exception\LogicException; +use Symfony\Component\Process\Exception\ProcessFailedException; +use Symfony\Component\Process\Exception\ProcessSignaledException; use Symfony\Component\Process\Exception\ProcessTimedOutException; use Symfony\Component\Process\Exception\RuntimeException; use Symfony\Component\Process\InputStream; @@ -78,13 +81,13 @@ public function testThatProcessDoesNotThrowWarningDuringRun() public function testNegativeTimeoutFromConstructor() { - $this->expectException(\Symfony\Component\Process\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->getProcess('', null, null, null, -1); } public function testNegativeTimeoutFromSetter() { - $this->expectException(\Symfony\Component\Process\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $p = $this->getProcess(''); $p->setTimeout(-1); } @@ -292,7 +295,7 @@ public function testSetInputWhileRunningThrowsAnException() */ public function testInvalidInput($value) { - $this->expectException(\Symfony\Component\Process\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('"Symfony\Component\Process\Process::setInput" only accepts strings, Traversable objects or stream resources.'); $process = $this->getProcess('foo'); $process->setInput($value); @@ -555,7 +558,7 @@ public function testSuccessfulMustRunHasCorrectExitCode() public function testMustRunThrowsException() { - $this->expectException(\Symfony\Component\Process\Exception\ProcessFailedException::class); + $this->expectException(ProcessFailedException::class); $process = $this->getProcess('exit 1'); $process->mustRun(); } @@ -707,7 +710,7 @@ public function testProcessIsSignaledIfStopped() public function testProcessThrowsExceptionWhenExternallySignaled() { - $this->expectException(\Symfony\Component\Process\Exception\ProcessSignaledException::class); + $this->expectException(ProcessSignaledException::class); $this->expectExceptionMessage('The process has been signaled with signal "9".'); if (!\function_exists('posix_kill')) { $this->markTestSkipped('Function posix_kill is required.'); @@ -1485,7 +1488,7 @@ public function testPreparedCommandWithQuoteInIt() public function testPreparedCommandWithMissingValue() { - $this->expectException(\Symfony\Component\Process\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Command line is missing a value for parameter "abc": echo "${:abc}"'); $p = Process::fromShellCommandline('echo "${:abc}"'); $p->run(null, ['bcd' => 'BCD']); @@ -1493,7 +1496,7 @@ public function testPreparedCommandWithMissingValue() public function testPreparedCommandWithNoValues() { - $this->expectException(\Symfony\Component\Process\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Command line is missing a value for parameter "abc": echo "${:abc}"'); $p = Process::fromShellCommandline('echo "${:abc}"'); $p->run(null, []); diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorArrayAccessTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorArrayAccessTest.php index 4a31588e3ee1..71e71a783860 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorArrayAccessTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorArrayAccessTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\PropertyAccess\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccessor; @@ -47,7 +48,7 @@ public function testGetValue($collection, $path, $value) public function testGetValueFailsIfNoSuchIndex() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchIndexException::class); + $this->expectException(NoSuchIndexException::class); $this->propertyAccessor = PropertyAccess::createPropertyAccessorBuilder() ->enableExceptionOnInvalidIndex() ->getPropertyAccessor(); diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTest.php index 13c977f418e1..0048a9525f07 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTest.php @@ -11,6 +11,8 @@ namespace Symfony\Component\PropertyAccess\Tests; +use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException; + class PropertyAccessorCollectionTest_Car { private $axes; @@ -121,8 +123,8 @@ public function testSetValueCallsAdderAndRemoverForCollections() public function testSetValueCallsAdderAndRemoverForNestedCollections() { - $car = $this->getMockBuilder(__CLASS__.'_CompositeCar')->getMock(); - $structure = $this->getMockBuilder(__CLASS__.'_CarStructure')->getMock(); + $car = $this->createMock(__CLASS__.'_CompositeCar'); + $structure = $this->createMock(__CLASS__.'_CarStructure'); $axesBefore = $this->getContainer([1 => 'second', 3 => 'fourth']); $axesAfter = $this->getContainer([0 => 'first', 1 => 'second', 2 => 'third']); @@ -148,9 +150,9 @@ public function testSetValueCallsAdderAndRemoverForNestedCollections() public function testSetValueFailsIfNoAdderNorRemoverFound() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException::class); + $this->expectException(NoSuchPropertyException::class); $this->expectExceptionMessageMatches('/Could not determine access type for property "axes" in class "Mock_PropertyAccessorCollectionTest_CarNoAdderAndRemover_[^"]*"./'); - $car = $this->getMockBuilder(__CLASS__.'_CarNoAdderAndRemover')->getMock(); + $car = $this->createMock(__CLASS__.'_CarNoAdderAndRemover'); $axesBefore = $this->getContainer([1 => 'second', 3 => 'fourth']); $axesAfter = $this->getContainer([0 => 'first', 1 => 'second', 2 => 'third']); @@ -187,7 +189,7 @@ public function testIsWritableReturnsFalseIfNoAdderNorRemoverExists() public function testSetValueFailsIfAdderAndRemoverExistButValueIsNotTraversable() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException::class); + $this->expectException(NoSuchPropertyException::class); $this->expectExceptionMessageMatches('/Could not determine access type for property "axes" in class "Symfony\\\\Component\\\\PropertyAccess\\\\Tests\\\\PropertyAccessorCollectionTest_Car[^"]*": The property "axes" in class "Symfony\\\\Component\\\\PropertyAccess\\\\Tests\\\\PropertyAccessorCollectionTest_Car[^"]*" can be defined with the methods "addAxis\(\)", "removeAxis\(\)" but the new value must be an array or an instance of \\\\Traversable, "string" given./'); $car = new PropertyAccessorCollectionTest_Car(); diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php index 779bb3b097c7..147be206ff67 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php @@ -13,7 +13,11 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Cache\Adapter\ArrayAdapter; +use Symfony\Component\PropertyAccess\Exception\AccessException; +use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException; use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException; +use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException; +use Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccessor; use Symfony\Component\PropertyAccess\Tests\Fixtures\ReturnTyped; @@ -101,7 +105,7 @@ public function testGetValue($objectOrArray, $path, $value) */ public function testGetValueThrowsExceptionIfPropertyNotFound($objectOrArray, $path) { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException::class); + $this->expectException(NoSuchPropertyException::class); $this->propertyAccessor->getValue($objectOrArray, $path); } @@ -138,7 +142,7 @@ public function testGetValueThrowsExceptionIfIndexNotFoundAndIndexExceptionsEnab */ public function testGetValueThrowsExceptionIfUninitializedProperty() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->expectExceptionMessage('The property "Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedProperty::$uninitialized" is not readable because it is typed "string". You should initialize it or declare a default value instead.'); $this->propertyAccessor->getValue(new UninitializedProperty(), 'uninitialized'); @@ -149,7 +153,7 @@ public function testGetValueThrowsExceptionIfUninitializedProperty() */ public function testGetValueThrowsExceptionIfUninitializedPropertyWithGetter() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->expectExceptionMessage('The method "Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedPrivateProperty::getUninitialized()" returned "null", but expected type "array". Did you forget to initialize a property or to make the return type nullable using "?array"?'); $this->propertyAccessor->getValue(new UninitializedPrivateProperty(), 'uninitialized'); @@ -160,7 +164,7 @@ public function testGetValueThrowsExceptionIfUninitializedPropertyWithGetter() */ public function testGetValueThrowsExceptionIfUninitializedPropertyWithGetterOfAnonymousClass() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->expectExceptionMessage('The method "class@anonymous::getUninitialized()" returned "null", but expected type "array". Did you forget to initialize a property or to make the return type nullable using "?array"?'); $object = eval('return new class() { @@ -180,7 +184,7 @@ public function getUninitialized(): array */ public function testGetValueThrowsExceptionIfUninitializedPropertyWithGetterOfAnonymousStdClass() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->expectExceptionMessage('The method "stdClass@anonymous::getUninitialized()" returned "null", but expected type "array". Did you forget to initialize a property or to make the return type nullable using "?array"?'); $object = eval('return new class() extends \stdClass { @@ -200,7 +204,7 @@ public function getUninitialized(): array */ public function testGetValueThrowsExceptionIfUninitializedPropertyWithGetterOfAnonymousChildClass() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\AccessException::class); + $this->expectException(AccessException::class); $this->expectExceptionMessage('The method "Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedPrivateProperty@anonymous::getUninitialized()" returned "null", but expected type "array". Did you forget to initialize a property or to make the return type nullable using "?array"?'); $object = eval('return new class() extends \Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedPrivateProperty {};'); @@ -259,7 +263,7 @@ public function testGetValueNotModifyObjectException() public function testGetValueDoesNotReadMagicCallByDefault() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException::class); + $this->expectException(NoSuchPropertyException::class); $this->propertyAccessor->getValue(new TestClassMagicCall('Bernhard'), 'magicCallProperty'); } @@ -283,7 +287,7 @@ public function testGetValueReadsMagicCallThatReturnsConstant() */ public function testGetValueThrowsExceptionIfNotObjectOrArray($objectOrArray, $path) { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $this->expectExceptionMessage('PropertyAccessor requires a graph of objects or arrays to operate on'); $this->propertyAccessor->getValue($objectOrArray, $path); } @@ -303,7 +307,7 @@ public function testSetValue($objectOrArray, $path) */ public function testSetValueThrowsExceptionIfPropertyNotFound($objectOrArray, $path) { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException::class); + $this->expectException(NoSuchPropertyException::class); $this->propertyAccessor->setValue($objectOrArray, $path, 'Updated'); } @@ -347,7 +351,7 @@ public function testSetValueUpdatesMagicSet() public function testSetValueThrowsExceptionIfThereAreMissingParameters() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException::class); + $this->expectException(NoSuchPropertyException::class); $object = new TestClass('Bernhard'); $this->propertyAccessor->setValue($object, 'publicAccessorWithMoreRequiredParameters', 'Updated'); @@ -355,7 +359,7 @@ public function testSetValueThrowsExceptionIfThereAreMissingParameters() public function testSetValueDoesNotUpdateMagicCallByDefault() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException::class); + $this->expectException(NoSuchPropertyException::class); $author = new TestClassMagicCall('Bernhard'); $this->propertyAccessor->setValue($author, 'magicCallProperty', 'Updated'); @@ -377,7 +381,7 @@ public function testSetValueUpdatesMagicCallIfEnabled() */ public function testSetValueThrowsExceptionIfNotObjectOrArray($objectOrArray, $path) { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $this->expectExceptionMessage('PropertyAccessor requires a graph of objects or arrays to operate on'); $this->propertyAccessor->setValue($objectOrArray, $path, 'value'); } @@ -613,7 +617,7 @@ public function testIsWritableForReferenceChainIssue($object, $path, $value) public function testThrowTypeError() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected argument of type "DateTime", "string" given at property path "date"'); $object = new TypeHinted(); @@ -622,7 +626,7 @@ public function testThrowTypeError() public function testThrowTypeErrorWithNullArgument() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected argument of type "DateTime", "null" given'); $object = new TypeHinted(); @@ -674,7 +678,7 @@ public function testAttributeWithSpecialChars() public function testThrowTypeErrorWithInterface() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected argument of type "Countable", "string" given'); $object = new TypeHinted(); @@ -694,7 +698,7 @@ public function testAnonymousClassRead() public function testAnonymousClassReadThrowExceptionOnInvalidPropertyPath() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException::class); + $this->expectException(NoSuchPropertyException::class); $obj = $this->generateAnonymousClass('bar'); $this->propertyAccessor->getValue($obj, 'invalid_property'); @@ -820,7 +824,7 @@ public function testAdderAndRemoverArePreferredOverSetterForSameSingularAndPlura public function testAdderWithoutRemover() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException::class); + $this->expectException(NoSuchPropertyException::class); $this->expectExceptionMessageMatches('/.*The add method "addFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidMethods" was found, but the corresponding remove method "removeFoo" was not found\./'); $object = new TestAdderRemoverInvalidMethods(); $this->propertyAccessor->setValue($object, 'foos', [1, 2]); @@ -828,7 +832,7 @@ public function testAdderWithoutRemover() public function testRemoverWithoutAdder() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException::class); + $this->expectException(NoSuchPropertyException::class); $this->expectExceptionMessageMatches('/.*The remove method "removeBar" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidMethods" was found, but the corresponding add method "addBar" was not found\./'); $object = new TestAdderRemoverInvalidMethods(); $this->propertyAccessor->setValue($object, 'bars', [1, 2]); @@ -836,7 +840,7 @@ public function testRemoverWithoutAdder() public function testAdderAndRemoveNeedsTheExactParametersDefined() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException::class); + $this->expectException(NoSuchPropertyException::class); $this->expectExceptionMessageMatches('/.*The method "addFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidArgumentLength" requires 0 arguments, but should accept only 1\. The method "removeFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidArgumentLength" requires 2 arguments, but should accept only 1\./'); $object = new TestAdderRemoverInvalidArgumentLength(); $this->propertyAccessor->setValue($object, 'foo', [1, 2]); @@ -844,7 +848,7 @@ public function testAdderAndRemoveNeedsTheExactParametersDefined() public function testSetterNeedsTheExactParametersDefined() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException::class); + $this->expectException(NoSuchPropertyException::class); $this->expectExceptionMessageMatches('/.*The method "setBar" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidArgumentLength" requires 2 arguments, but should accept only 1\./'); $object = new TestAdderRemoverInvalidArgumentLength(); $this->propertyAccessor->setValue($object, 'bar', [1, 2]); @@ -852,7 +856,7 @@ public function testSetterNeedsTheExactParametersDefined() public function testSetterNeedsPublicAccess() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException::class); + $this->expectException(NoSuchPropertyException::class); $this->expectExceptionMessageMatches('/.*The method "setFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestClassSetValue" was found but does not have public access./'); $object = new TestClassSetValue(0); $this->propertyAccessor->setValue($object, 'foo', 1); diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyPathTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyPathTest.php index 6b08d2b65d51..87967373e38f 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyPathTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyPathTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\PropertyAccess\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException; +use Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException; use Symfony\Component\PropertyAccess\PropertyPath; class PropertyPathTest extends TestCase @@ -25,13 +27,13 @@ public function testToString() public function testDotIsRequiredBeforeProperty() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException::class); + $this->expectException(InvalidPropertyPathException::class); new PropertyPath('[index]property'); } public function testDotCannotBePresentAtTheBeginning() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException::class); + $this->expectException(InvalidPropertyPathException::class); new PropertyPath('.property'); } @@ -53,25 +55,25 @@ public function providePathsContainingUnexpectedCharacters() */ public function testUnexpectedCharacters($path) { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException::class); + $this->expectException(InvalidPropertyPathException::class); new PropertyPath($path); } public function testPathCannotBeEmpty() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException::class); + $this->expectException(InvalidPropertyPathException::class); new PropertyPath(''); } public function testPathCannotBeNull() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); new PropertyPath(null); } public function testPathCannotBeFalse() { - $this->expectException(\Symfony\Component\PropertyAccess\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); new PropertyPath(false); } diff --git a/src/Symfony/Component/PropertyInfo/Tests/AbstractPropertyInfoExtractorTest.php b/src/Symfony/Component/PropertyInfo/Tests/AbstractPropertyInfoExtractorTest.php index 66041a309cf8..ce5a43c0ddaa 100644 --- a/src/Symfony/Component/PropertyInfo/Tests/AbstractPropertyInfoExtractorTest.php +++ b/src/Symfony/Component/PropertyInfo/Tests/AbstractPropertyInfoExtractorTest.php @@ -12,8 +12,12 @@ namespace Symfony\Component\PropertyInfo\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\PropertyInfo\PropertyAccessExtractorInterface; +use Symfony\Component\PropertyInfo\PropertyDescriptionExtractorInterface; use Symfony\Component\PropertyInfo\PropertyInfoExtractor; +use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface; use Symfony\Component\PropertyInfo\PropertyInitializableExtractorInterface; +use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface; use Symfony\Component\PropertyInfo\Tests\Fixtures\DummyExtractor; use Symfony\Component\PropertyInfo\Tests\Fixtures\NullExtractor; use Symfony\Component\PropertyInfo\Type; @@ -36,10 +40,10 @@ protected function setUp(): void public function testInstanceOf() { - $this->assertInstanceOf(\Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface::class, $this->propertyInfo); - $this->assertInstanceOf(\Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface::class, $this->propertyInfo); - $this->assertInstanceOf(\Symfony\Component\PropertyInfo\PropertyDescriptionExtractorInterface::class, $this->propertyInfo); - $this->assertInstanceOf(\Symfony\Component\PropertyInfo\PropertyAccessExtractorInterface::class, $this->propertyInfo); + $this->assertInstanceOf(PropertyInfoExtractorInterface::class, $this->propertyInfo); + $this->assertInstanceOf(PropertyTypeExtractorInterface::class, $this->propertyInfo); + $this->assertInstanceOf(PropertyDescriptionExtractorInterface::class, $this->propertyInfo); + $this->assertInstanceOf(PropertyAccessExtractorInterface::class, $this->propertyInfo); $this->assertInstanceOf(PropertyInitializableExtractorInterface::class, $this->propertyInfo); } diff --git a/src/Symfony/Component/Routing/Tests/Generator/Dumper/CompiledUrlGeneratorDumperTest.php b/src/Symfony/Component/Routing/Tests/Generator/Dumper/CompiledUrlGeneratorDumperTest.php index ee71ce98a186..4f3ea6eb2251 100644 --- a/src/Symfony/Component/Routing/Tests/Generator/Dumper/CompiledUrlGeneratorDumperTest.php +++ b/src/Symfony/Component/Routing/Tests/Generator/Dumper/CompiledUrlGeneratorDumperTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Routing\Tests\Generator\Dumper; use PHPUnit\Framework\TestCase; +use Symfony\Component\Routing\Exception\RouteNotFoundException; use Symfony\Component\Routing\Generator\CompiledUrlGenerator; use Symfony\Component\Routing\Generator\Dumper\CompiledUrlGeneratorDumper; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; @@ -118,7 +119,7 @@ public function testDumpWithSimpleLocalizedRoutes() public function testDumpWithRouteNotFoundLocalizedRoutes() { - $this->expectException(\Symfony\Component\Routing\Exception\RouteNotFoundException::class); + $this->expectException(RouteNotFoundException::class); $this->expectExceptionMessage('Unable to generate a URL for the named route "test" as such route does not exist.'); $this->routeCollection->add('test.en', (new Route('/testing/is/fun'))->setDefault('_locale', 'en')->setDefault('_canonical_route', 'test')->setRequirement('_locale', 'en')); @@ -188,7 +189,7 @@ public function testDumpWithoutRoutes() public function testGenerateNonExistingRoute() { - $this->expectException(\Symfony\Component\Routing\Exception\RouteNotFoundException::class); + $this->expectException(RouteNotFoundException::class); $this->routeCollection->add('Test', new Route('/test')); file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump()); diff --git a/src/Symfony/Component/Routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.php b/src/Symfony/Component/Routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.php index f25d6387921c..ca25f4a8e8ab 100644 --- a/src/Symfony/Component/Routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.php +++ b/src/Symfony/Component/Routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Routing\Tests\Generator\Dumper; use PHPUnit\Framework\TestCase; +use Symfony\Component\Routing\Exception\RouteNotFoundException; use Symfony\Component\Routing\Generator\Dumper\PhpGeneratorDumper; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\RequestContext; @@ -124,7 +125,7 @@ public function testDumpWithSimpleLocalizedRoutes() public function testDumpWithRouteNotFoundLocalizedRoutes() { - $this->expectException(\Symfony\Component\Routing\Exception\RouteNotFoundException::class); + $this->expectException(RouteNotFoundException::class); $this->expectExceptionMessage('Unable to generate a URL for the named route "test" as such route does not exist.'); $this->routeCollection->add('test.en', (new Route('/testing/is/fun'))->setDefault('_locale', 'en')->setDefault('_canonical_route', 'test')->setRequirement('_locale', 'en')); @@ -204,7 +205,7 @@ public function testDumpWithoutRoutes() public function testGenerateNonExistingRoute() { - $this->expectException(\Symfony\Component\Routing\Exception\RouteNotFoundException::class); + $this->expectException(RouteNotFoundException::class); $this->routeCollection->add('Test', new Route('/test')); file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(['class' => 'NonExistingRoutesUrlGenerator'])); diff --git a/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php b/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php index 6246b90e6a33..f006f4ce9d58 100644 --- a/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php +++ b/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php @@ -12,6 +12,10 @@ namespace Symfony\Component\Routing\Tests\Generator; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; +use Symfony\Component\Routing\Exception\InvalidParameterException; +use Symfony\Component\Routing\Exception\MissingMandatoryParametersException; +use Symfony\Component\Routing\Exception\RouteNotFoundException; use Symfony\Component\Routing\Generator\UrlGenerator; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\RequestContext; @@ -78,7 +82,7 @@ public function testRelativeUrlWithNullParameter() public function testRelativeUrlWithNullParameterButNotOptional() { - $this->expectException(\Symfony\Component\Routing\Exception\InvalidParameterException::class); + $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/testing/{foo}/bar', ['foo' => null])); // This must raise an exception because the default requirement for "foo" is "[^/]+" which is not met with these params. // Generating path "/testing//bar" would be wrong as matching this route would fail. @@ -264,14 +268,14 @@ public function testDumpWithLocalizedRoutesPreserveTheGoodLocaleInTheUrl() public function testGenerateWithoutRoutes() { - $this->expectException(\Symfony\Component\Routing\Exception\RouteNotFoundException::class); + $this->expectException(RouteNotFoundException::class); $routes = $this->getRoutes('foo', new Route('/testing/{foo}')); $this->getGenerator($routes)->generate('test', [], UrlGeneratorInterface::ABSOLUTE_URL); } public function testGenerateWithInvalidLocale() { - $this->expectException(\Symfony\Component\Routing\Exception\RouteNotFoundException::class); + $this->expectException(RouteNotFoundException::class); $routes = new RouteCollection(); $route = new Route(''); @@ -293,21 +297,21 @@ public function testGenerateWithInvalidLocale() public function testGenerateForRouteWithoutMandatoryParameter() { - $this->expectException(\Symfony\Component\Routing\Exception\MissingMandatoryParametersException::class); + $this->expectException(MissingMandatoryParametersException::class); $routes = $this->getRoutes('test', new Route('/testing/{foo}')); $this->getGenerator($routes)->generate('test', [], UrlGeneratorInterface::ABSOLUTE_URL); } public function testGenerateForRouteWithInvalidOptionalParameter() { - $this->expectException(\Symfony\Component\Routing\Exception\InvalidParameterException::class); + $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/testing/{foo}', ['foo' => '1'], ['foo' => 'd+'])); $this->getGenerator($routes)->generate('test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_URL); } public function testGenerateForRouteWithInvalidParameter() { - $this->expectException(\Symfony\Component\Routing\Exception\InvalidParameterException::class); + $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/testing/{foo}', [], ['foo' => '1|2'])); $this->getGenerator($routes)->generate('test', ['foo' => '0'], UrlGeneratorInterface::ABSOLUTE_URL); } @@ -323,7 +327,7 @@ public function testGenerateForRouteWithInvalidOptionalParameterNonStrict() public function testGenerateForRouteWithInvalidOptionalParameterNonStrictWithLogger() { $routes = $this->getRoutes('test', new Route('/testing/{foo}', ['foo' => '1'], ['foo' => 'd+'])); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $logger->expects($this->once()) ->method('error'); $generator = $this->getGenerator($routes, [], $logger); @@ -341,21 +345,21 @@ public function testGenerateForRouteWithInvalidParameterButDisabledRequirementsC public function testGenerateForRouteWithInvalidMandatoryParameter() { - $this->expectException(\Symfony\Component\Routing\Exception\InvalidParameterException::class); + $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/testing/{foo}', [], ['foo' => 'd+'])); $this->getGenerator($routes)->generate('test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_URL); } public function testGenerateForRouteWithInvalidUtf8Parameter() { - $this->expectException(\Symfony\Component\Routing\Exception\InvalidParameterException::class); + $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/testing/{foo}', [], ['foo' => '\pL+'], ['utf8' => true])); $this->getGenerator($routes)->generate('test', ['foo' => 'abc123'], UrlGeneratorInterface::ABSOLUTE_URL); } public function testRequiredParamAndEmptyPassed() { - $this->expectException(\Symfony\Component\Routing\Exception\InvalidParameterException::class); + $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/{slug}', [], ['slug' => '.+'])); $this->getGenerator($routes)->generate('test', ['slug' => '']); } @@ -476,7 +480,7 @@ public function testAdjacentVariables() // The default requirement for 'x' should not allow the separator '.' in this case because it would otherwise match everything // and following optional variables like _format could never match. - $this->expectException(\Symfony\Component\Routing\Exception\InvalidParameterException::class); + $this->expectException(InvalidParameterException::class); $generator->generate('test', ['x' => 'do.t', 'y' => '123', 'z' => 'bar', '_format' => 'xml']); } @@ -517,7 +521,7 @@ public function testImportantVariable() public function testImportantVariableWithNoDefault() { - $this->expectException(\Symfony\Component\Routing\Exception\MissingMandatoryParametersException::class); + $this->expectException(MissingMandatoryParametersException::class); $routes = $this->getRoutes('test', new Route('/{page}.{!_format}')); $generator = $this->getGenerator($routes); @@ -526,14 +530,14 @@ public function testImportantVariableWithNoDefault() public function testDefaultRequirementOfVariableDisallowsSlash() { - $this->expectException(\Symfony\Component\Routing\Exception\InvalidParameterException::class); + $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/{page}.{_format}')); $this->getGenerator($routes)->generate('test', ['page' => 'index', '_format' => 'sl/ash']); } public function testDefaultRequirementOfVariableDisallowsNextSeparator() { - $this->expectException(\Symfony\Component\Routing\Exception\InvalidParameterException::class); + $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/{page}.{_format}')); $this->getGenerator($routes)->generate('test', ['page' => 'do.t', '_format' => 'html']); } @@ -561,21 +565,21 @@ public function testWithHostSameAsContextAndAbsolute() public function testUrlWithInvalidParameterInHost() { - $this->expectException(\Symfony\Component\Routing\Exception\InvalidParameterException::class); + $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/', [], ['foo' => 'bar'], [], '{foo}.example.com')); $this->getGenerator($routes)->generate('test', ['foo' => 'baz'], UrlGeneratorInterface::ABSOLUTE_PATH); } public function testUrlWithInvalidParameterInHostWhenParamHasADefaultValue() { - $this->expectException(\Symfony\Component\Routing\Exception\InvalidParameterException::class); + $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/', ['foo' => 'bar'], ['foo' => 'bar'], [], '{foo}.example.com')); $this->getGenerator($routes)->generate('test', ['foo' => 'baz'], UrlGeneratorInterface::ABSOLUTE_PATH); } public function testUrlWithInvalidParameterEqualsDefaultValueInHost() { - $this->expectException(\Symfony\Component\Routing\Exception\InvalidParameterException::class); + $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/', ['foo' => 'baz'], ['foo' => 'bar'], [], '{foo}.example.com')); $this->getGenerator($routes)->generate('test', ['foo' => 'baz'], UrlGeneratorInterface::ABSOLUTE_PATH); } diff --git a/src/Symfony/Component/Routing/Tests/Loader/AbstractAnnotationLoaderTest.php b/src/Symfony/Component/Routing/Tests/Loader/AbstractAnnotationLoaderTest.php index 8b26c209d38a..fea06e51dcdc 100644 --- a/src/Symfony/Component/Routing/Tests/Loader/AbstractAnnotationLoaderTest.php +++ b/src/Symfony/Component/Routing/Tests/Loader/AbstractAnnotationLoaderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Routing\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Routing\Loader\AnnotationClassLoader; abstract class AbstractAnnotationLoaderTest extends TestCase { @@ -25,7 +26,7 @@ public function getReader() public function getClassLoader($reader) { - return $this->getMockBuilder(\Symfony\Component\Routing\Loader\AnnotationClassLoader::class) + return $this->getMockBuilder(AnnotationClassLoader::class) ->setConstructorArgs([$reader]) ->getMockForAbstractClass() ; diff --git a/src/Symfony/Component/Routing/Tests/Loader/PhpFileLoaderTest.php b/src/Symfony/Component/Routing/Tests/Loader/PhpFileLoaderTest.php index e48114abd2fc..70d45fc2383e 100644 --- a/src/Symfony/Component/Routing/Tests/Loader/PhpFileLoaderTest.php +++ b/src/Symfony/Component/Routing/Tests/Loader/PhpFileLoaderTest.php @@ -22,7 +22,7 @@ class PhpFileLoaderTest extends TestCase { public function testSupports() { - $loader = new PhpFileLoader($this->getMockBuilder(FileLocator::class)->getMock()); + $loader = new PhpFileLoader($this->createMock(FileLocator::class)); $this->assertTrue($loader->supports('foo.php'), '->supports() returns true if the resource is loadable'); $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable'); diff --git a/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php b/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php index 1a8e4bb5dffc..6a7284d8ff97 100644 --- a/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php +++ b/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php @@ -23,7 +23,7 @@ class XmlFileLoaderTest extends TestCase { public function testSupports() { - $loader = new XmlFileLoader($this->getMockBuilder(FileLocator::class)->getMock()); + $loader = new XmlFileLoader($this->createMock(FileLocator::class)); $this->assertTrue($loader->supports('foo.xml'), '->supports() returns true if the resource is loadable'); $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable'); diff --git a/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php index 7030265cf7ec..1efab54c6d20 100644 --- a/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php @@ -22,7 +22,7 @@ class YamlFileLoaderTest extends TestCase { public function testSupports() { - $loader = new YamlFileLoader($this->getMockBuilder(FileLocator::class)->getMock()); + $loader = new YamlFileLoader($this->createMock(FileLocator::class)); $this->assertTrue($loader->supports('foo.yml'), '->supports() returns true if the resource is loadable'); $this->assertTrue($loader->supports('foo.yaml'), '->supports() returns true if the resource is loadable'); diff --git a/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php b/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php index 83dfe2d62d8e..e7e49a212bd4 100644 --- a/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php +++ b/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php @@ -11,6 +11,8 @@ namespace Symfony\Component\Routing\Tests\Matcher; +use Symfony\Component\Routing\Exception\ResourceNotFoundException; +use Symfony\Component\Routing\Matcher\RedirectableUrlMatcher; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; @@ -39,7 +41,7 @@ public function testExtraTrailingSlash() public function testRedirectWhenNoSlashForNonSafeMethod() { - $this->expectException(\Symfony\Component\Routing\Exception\ResourceNotFoundException::class); + $this->expectException(ResourceNotFoundException::class); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo/')); @@ -209,6 +211,6 @@ public function testTrailingRequirementWithDefault_A() protected function getUrlMatcher(RouteCollection $routes, RequestContext $context = null) { - return $this->getMockForAbstractClass(\Symfony\Component\Routing\Matcher\RedirectableUrlMatcher::class, [$routes, $context ?: new RequestContext()]); + return $this->getMockForAbstractClass(RedirectableUrlMatcher::class, [$routes, $context ?: new RequestContext()]); } } diff --git a/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php b/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php index 3adb4a9d58db..7297a887731d 100644 --- a/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php +++ b/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Routing\Exception\MethodNotAllowedException; +use Symfony\Component\Routing\Exception\NoConfigurationException; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; @@ -687,7 +688,7 @@ public function testHostIsCaseInsensitive() public function testNoConfiguration() { - $this->expectException(\Symfony\Component\Routing\Exception\NoConfigurationException::class); + $this->expectException(NoConfigurationException::class); $coll = new RouteCollection(); $matcher = $this->getUrlMatcher($coll); diff --git a/src/Symfony/Component/Routing/Tests/RouteCollectionBuilderTest.php b/src/Symfony/Component/Routing/Tests/RouteCollectionBuilderTest.php index f995d94d1d5a..de6a27a3454e 100644 --- a/src/Symfony/Component/Routing/Tests/RouteCollectionBuilderTest.php +++ b/src/Symfony/Component/Routing/Tests/RouteCollectionBuilderTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\FileLocator; +use Symfony\Component\Config\Loader\LoaderInterface; +use Symfony\Component\Config\Loader\LoaderResolverInterface; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Routing\Loader\YamlFileLoader; use Symfony\Component\Routing\Route; @@ -23,8 +25,8 @@ class RouteCollectionBuilderTest extends TestCase { public function testImport() { - $resolvedLoader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); - $resolver = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderResolverInterface::class)->getMock(); + $resolvedLoader = $this->createMock(LoaderInterface::class); + $resolver = $this->createMock(LoaderResolverInterface::class); $resolver->expects($this->once()) ->method('resolve') ->with('admin_routing.yml', 'yaml') @@ -41,7 +43,7 @@ public function testImport() ->with('admin_routing.yml', 'yaml') ->willReturn($expectedCollection); - $loader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loader->expects($this->any()) ->method('getResolver') ->willReturn($resolver); @@ -101,7 +103,7 @@ public function testFlushOrdering() $importedCollection->add('imported_route1', new Route('/imported/foo1')); $importedCollection->add('imported_route2', new Route('/imported/foo2')); - $loader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); // make this loader able to do the import - keeps mocking simple $loader->expects($this->any()) ->method('supports') @@ -264,7 +266,7 @@ public function providePrefixTests() public function testFlushSetsPrefixedWithMultipleLevels() { - $loader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $routes = new RouteCollectionBuilder($loader); $routes->add('homepage', 'MainController::homepageAction', 'homepage'); @@ -342,7 +344,7 @@ public function testAddsThePrefixOnlyOnceWhenLoadingMultipleCollections() $secondCollection = new RouteCollection(); $secondCollection->add('b', new Route('/b')); - $loader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loader->expects($this->any()) ->method('supports') ->willReturn(true); diff --git a/src/Symfony/Component/Routing/Tests/RouteTest.php b/src/Symfony/Component/Routing/Tests/RouteTest.php index a630afefca95..a85824b3fbe7 100644 --- a/src/Symfony/Component/Routing/Tests/RouteTest.php +++ b/src/Symfony/Component/Routing/Tests/RouteTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Routing\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Routing\CompiledRoute; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\Tests\Fixtures\CustomCompiledRoute; use Symfony\Component\Routing\Tests\Fixtures\CustomRouteCompiler; @@ -188,7 +189,7 @@ public function testCondition() public function testCompile() { $route = new Route('/{foo}'); - $this->assertInstanceOf(\Symfony\Component\Routing\CompiledRoute::class, $compiled = $route->compile(), '->compile() returns a compiled route'); + $this->assertInstanceOf(CompiledRoute::class, $compiled = $route->compile(), '->compile() returns a compiled route'); $this->assertSame($compiled, $route->compile(), '->compile() only compiled the route once if unchanged'); $route->setRequirement('foo', '.*'); $this->assertNotSame($compiled, $route->compile(), '->compile() recompiles if the route was modified'); diff --git a/src/Symfony/Component/Routing/Tests/RouterTest.php b/src/Symfony/Component/Routing/Tests/RouterTest.php index 9c8dda7ac1ed..7d9d3556deb8 100644 --- a/src/Symfony/Component/Routing/Tests/RouterTest.php +++ b/src/Symfony/Component/Routing/Tests/RouterTest.php @@ -12,7 +12,13 @@ namespace Symfony\Component\Routing\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Routing\Generator\UrlGenerator; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use Symfony\Component\Routing\Matcher\RequestMatcherInterface; +use Symfony\Component\Routing\Matcher\UrlMatcher; +use Symfony\Component\Routing\Matcher\UrlMatcherInterface; use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Router; @@ -26,7 +32,7 @@ class RouterTest extends TestCase protected function setUp(): void { - $this->loader = $this->getMockBuilder(\Symfony\Component\Config\Loader\LoaderInterface::class)->getMock(); + $this->loader = $this->createMock(LoaderInterface::class); $this->router = new Router($this->loader, 'routing.yml'); $this->cacheDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('router_', true); @@ -111,7 +117,7 @@ public function testMatcherIsCreatedIfCacheIsNotConfigured() ->method('load')->with('routing.yml', null) ->willReturn(new RouteCollection()); - $this->assertInstanceOf(\Symfony\Component\Routing\Matcher\UrlMatcher::class, $this->router->getMatcher()); + $this->assertInstanceOf(UrlMatcher::class, $this->router->getMatcher()); } public function testGeneratorIsCreatedIfCacheIsNotConfigured() @@ -122,12 +128,12 @@ public function testGeneratorIsCreatedIfCacheIsNotConfigured() ->method('load')->with('routing.yml', null) ->willReturn(new RouteCollection()); - $this->assertInstanceOf(\Symfony\Component\Routing\Generator\UrlGenerator::class, $this->router->getGenerator()); + $this->assertInstanceOf(UrlGenerator::class, $this->router->getGenerator()); } public function testMatchRequestWithUrlMatcherInterface() { - $matcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\UrlMatcherInterface::class)->getMock(); + $matcher = $this->createMock(UrlMatcherInterface::class); $matcher->expects($this->once())->method('match'); $p = new \ReflectionProperty($this->router, 'matcher'); @@ -139,7 +145,7 @@ public function testMatchRequestWithUrlMatcherInterface() public function testMatchRequestWithRequestMatcherInterface() { - $matcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\RequestMatcherInterface::class)->getMock(); + $matcher = $this->createMock(RequestMatcherInterface::class); $matcher->expects($this->once())->method('matchRequest'); $p = new \ReflectionProperty($this->router, 'matcher'); @@ -161,7 +167,7 @@ public function testDefaultLocaleIsPassedToGeneratorClass() $generator = $router->getGenerator(); - $this->assertInstanceOf(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class, $generator); + $this->assertInstanceOf(UrlGeneratorInterface::class, $generator); $p = new \ReflectionProperty($generator, 'defaultLocale'); $p->setAccessible(true); @@ -181,7 +187,7 @@ public function testDefaultLocaleIsPassedToCompiledGeneratorCacheClass() $generator = $router->getGenerator(); - $this->assertInstanceOf(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class, $generator); + $this->assertInstanceOf(UrlGeneratorInterface::class, $generator); $p = new \ReflectionProperty($generator, 'defaultLocale'); $p->setAccessible(true); @@ -205,7 +211,7 @@ public function testDefaultLocaleIsPassedToNotCompiledGeneratorCacheClass() $generator = $router->getGenerator(); - $this->assertInstanceOf(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class, $generator); + $this->assertInstanceOf(UrlGeneratorInterface::class, $generator); $p = new \ReflectionProperty($generator, 'defaultLocale'); $p->setAccessible(true); diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationProviderManagerTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationProviderManagerTest.php index e7f13b8e6df8..db1e388703bb 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationProviderManagerTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationProviderManagerTest.php @@ -12,7 +12,9 @@ namespace Symfony\Component\Security\Core\Tests\Authentication; use PHPUnit\Framework\TestCase; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager; +use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; use Symfony\Component\Security\Core\AuthenticationEvents; @@ -35,7 +37,7 @@ public function testAuthenticateWithProvidersWithIncorrectInterface() $this->expectException(\InvalidArgumentException::class); (new AuthenticationProviderManager([ new \stdClass(), - ]))->authenticate($this->getMockBuilder(TokenInterface::class)->getMock()); + ]))->authenticate($this->createMock(TokenInterface::class)); } public function testAuthenticateWhenNoProviderSupportsToken() @@ -45,7 +47,7 @@ public function testAuthenticateWhenNoProviderSupportsToken() ]); try { - $manager->authenticate($token = $this->getMockBuilder(TokenInterface::class)->getMock()); + $manager->authenticate($token = $this->createMock(TokenInterface::class)); $this->fail(); } catch (ProviderNotFoundException $e) { $this->assertSame($token, $e->getToken()); @@ -54,10 +56,10 @@ public function testAuthenticateWhenNoProviderSupportsToken() public function testAuthenticateWhenProviderReturnsAccountStatusException() { - $secondAuthenticationProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface::class)->getMock(); + $secondAuthenticationProvider = $this->createMock(AuthenticationProviderInterface::class); $manager = new AuthenticationProviderManager([ - $this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AccountStatusException'), + $this->getAuthenticationProvider(true, null, AccountStatusException::class), $secondAuthenticationProvider, ]); @@ -65,7 +67,7 @@ public function testAuthenticateWhenProviderReturnsAccountStatusException() $secondAuthenticationProvider->expects($this->never())->method('supports'); try { - $manager->authenticate($token = $this->getMockBuilder(TokenInterface::class)->getMock()); + $manager->authenticate($token = $this->createMock(TokenInterface::class)); $this->fail(); } catch (AccountStatusException $e) { $this->assertSame($token, $e->getToken()); @@ -75,11 +77,11 @@ public function testAuthenticateWhenProviderReturnsAccountStatusException() public function testAuthenticateWhenProviderReturnsAuthenticationException() { $manager = new AuthenticationProviderManager([ - $this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AuthenticationException'), + $this->getAuthenticationProvider(true, null, AuthenticationException::class), ]); try { - $manager->authenticate($token = $this->getMockBuilder(TokenInterface::class)->getMock()); + $manager->authenticate($token = $this->createMock(TokenInterface::class)); $this->fail(); } catch (AuthenticationException $e) { $this->assertSame($token, $e->getToken()); @@ -89,27 +91,27 @@ public function testAuthenticateWhenProviderReturnsAuthenticationException() public function testAuthenticateWhenOneReturnsAuthenticationExceptionButNotAll() { $manager = new AuthenticationProviderManager([ - $this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AuthenticationException'), - $this->getAuthenticationProvider(true, $expected = $this->getMockBuilder(TokenInterface::class)->getMock()), + $this->getAuthenticationProvider(true, null, AuthenticationException::class), + $this->getAuthenticationProvider(true, $expected = $this->createMock(TokenInterface::class)), ]); - $token = $manager->authenticate($this->getMockBuilder(TokenInterface::class)->getMock()); + $token = $manager->authenticate($this->createMock(TokenInterface::class)); $this->assertSame($expected, $token); } public function testAuthenticateReturnsTokenOfTheFirstMatchingProvider() { - $second = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface::class)->getMock(); + $second = $this->createMock(AuthenticationProviderInterface::class); $second ->expects($this->never()) ->method('supports') ; $manager = new AuthenticationProviderManager([ - $this->getAuthenticationProvider(true, $expected = $this->getMockBuilder(TokenInterface::class)->getMock()), + $this->getAuthenticationProvider(true, $expected = $this->createMock(TokenInterface::class)), $second, ]); - $token = $manager->authenticate($this->getMockBuilder(TokenInterface::class)->getMock()); + $token = $manager->authenticate($this->createMock(TokenInterface::class)); $this->assertSame($expected, $token); } @@ -119,25 +121,25 @@ public function testEraseCredentialFlag() $this->getAuthenticationProvider(true, $token = new UsernamePasswordToken('foo', 'bar', 'key')), ]); - $token = $manager->authenticate($this->getMockBuilder(TokenInterface::class)->getMock()); + $token = $manager->authenticate($this->createMock(TokenInterface::class)); $this->assertEquals('', $token->getCredentials()); $manager = new AuthenticationProviderManager([ $this->getAuthenticationProvider(true, $token = new UsernamePasswordToken('foo', 'bar', 'key')), ], false); - $token = $manager->authenticate($this->getMockBuilder(TokenInterface::class)->getMock()); + $token = $manager->authenticate($this->createMock(TokenInterface::class)); $this->assertEquals('bar', $token->getCredentials()); } public function testAuthenticateDispatchesAuthenticationFailureEvent() { $token = new UsernamePasswordToken('foo', 'bar', 'key'); - $provider = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface::class)->getMock(); + $provider = $this->createMock(AuthenticationProviderInterface::class); $provider->expects($this->once())->method('supports')->willReturn(true); $provider->expects($this->once())->method('authenticate')->willThrowException($exception = new AuthenticationException()); - $dispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class)->getMock(); + $dispatcher = $this->createMock(EventDispatcherInterface::class); $dispatcher ->expects($this->once()) ->method('dispatch') @@ -158,11 +160,11 @@ public function testAuthenticateDispatchesAuthenticationSuccessEvent() { $token = new UsernamePasswordToken('foo', 'bar', 'key'); - $provider = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface::class)->getMock(); + $provider = $this->createMock(AuthenticationProviderInterface::class); $provider->expects($this->once())->method('supports')->willReturn(true); $provider->expects($this->once())->method('authenticate')->willReturn($token); - $dispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class)->getMock(); + $dispatcher = $this->createMock(EventDispatcherInterface::class); $dispatcher ->expects($this->once()) ->method('dispatch') @@ -176,7 +178,7 @@ public function testAuthenticateDispatchesAuthenticationSuccessEvent() protected function getAuthenticationProvider($supports, $token = null, $exception = null) { - $provider = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface::class)->getMock(); + $provider = $this->createMock(AuthenticationProviderInterface::class); $provider->expects($this->once()) ->method('supports') ->willReturn($supports) diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationTrustResolverTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationTrustResolverTest.php index ca352da31f37..eb82a596bcfa 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationTrustResolverTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationTrustResolverTest.php @@ -124,7 +124,7 @@ public function testisFullFledgedWithClassAsConstructorButStillExtending() protected function getToken() { - return $this->getMockBuilder(TokenInterface::class)->getMock(); + return $this->createMock(TokenInterface::class); } protected function getAnonymousToken() diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/AnonymousAuthenticationProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/AnonymousAuthenticationProviderTest.php index e0fe4a8a1118..5aa23d981cf5 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/AnonymousAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/AnonymousAuthenticationProviderTest.php @@ -13,6 +13,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Authentication\Provider\AnonymousAuthenticationProvider; +use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; +use Symfony\Component\Security\Core\Exception\AuthenticationException; +use Symfony\Component\Security\Core\Exception\BadCredentialsException; class AnonymousAuthenticationProviderTest extends TestCase { @@ -21,21 +25,21 @@ public function testSupports() $provider = $this->getProvider('foo'); $this->assertTrue($provider->supports($this->getSupportedToken('foo'))); - $this->assertFalse($provider->supports($this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock())); + $this->assertFalse($provider->supports($this->createMock(TokenInterface::class))); } public function testAuthenticateWhenTokenIsNotSupported() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AuthenticationException::class); + $this->expectException(AuthenticationException::class); $this->expectExceptionMessage('The token is not supported by this authentication provider.'); $provider = $this->getProvider('foo'); - $provider->authenticate($this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()); + $provider->authenticate($this->createMock(TokenInterface::class)); } public function testAuthenticateWhenSecretIsNotValid() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $provider = $this->getProvider('foo'); $provider->authenticate($this->getSupportedToken('bar')); @@ -51,7 +55,7 @@ public function testAuthenticate() protected function getSupportedToken($secret) { - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\AnonymousToken::class)->setMethods(['getSecret'])->disableOriginalConstructor()->getMock(); + $token = $this->getMockBuilder(AnonymousToken::class)->setMethods(['getSecret'])->disableOriginalConstructor()->getMock(); $token->expects($this->any()) ->method('getSecret') ->willReturn($secret) diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/DaoAuthenticationProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/DaoAuthenticationProviderTest.php index 37f690d0b559..ce2a4af55021 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/DaoAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/DaoAuthenticationProviderTest.php @@ -13,18 +13,25 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider; +use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; +use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface; +use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface; use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder; +use Symfony\Component\Security\Core\Exception\AuthenticationServiceException; +use Symfony\Component\Security\Core\Exception\BadCredentialsException; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\Tests\Encoder\TestPasswordEncoderInterface; use Symfony\Component\Security\Core\User\PasswordUpgraderInterface; use Symfony\Component\Security\Core\User\User; +use Symfony\Component\Security\Core\User\UserCheckerInterface; +use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; class DaoAuthenticationProviderTest extends TestCase { public function testRetrieveUserWhenProviderDoesNotReturnAnUserInterface() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AuthenticationServiceException::class); + $this->expectException(AuthenticationServiceException::class); $provider = $this->getProvider('fabien'); $method = new \ReflectionMethod($provider, 'retrieveUser'); $method->setAccessible(true); @@ -35,13 +42,13 @@ public function testRetrieveUserWhenProviderDoesNotReturnAnUserInterface() public function testRetrieveUserWhenUsernameIsNotFound() { $this->expectException(UsernameNotFoundException::class); - $userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock(); + $userProvider = $this->createMock(UserProviderInterface::class); $userProvider->expects($this->once()) ->method('loadUserByUsername') ->willThrowException(new UsernameNotFoundException()) ; - $provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(), 'key', $this->getMockBuilder(\Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface::class)->getMock()); + $provider = new DaoAuthenticationProvider($userProvider, $this->createMock(UserCheckerInterface::class), 'key', $this->createMock(EncoderFactoryInterface::class)); $method = new \ReflectionMethod($provider, 'retrieveUser'); $method->setAccessible(true); @@ -50,14 +57,14 @@ public function testRetrieveUserWhenUsernameIsNotFound() public function testRetrieveUserWhenAnExceptionOccurs() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AuthenticationServiceException::class); - $userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock(); + $this->expectException(AuthenticationServiceException::class); + $userProvider = $this->createMock(UserProviderInterface::class); $userProvider->expects($this->once()) ->method('loadUserByUsername') ->willThrowException(new \RuntimeException()) ; - $provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(), 'key', $this->getMockBuilder(\Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface::class)->getMock()); + $provider = new DaoAuthenticationProvider($userProvider, $this->createMock(UserCheckerInterface::class), 'key', $this->createMock(EncoderFactoryInterface::class)); $method = new \ReflectionMethod($provider, 'retrieveUser'); $method->setAccessible(true); @@ -66,19 +73,19 @@ public function testRetrieveUserWhenAnExceptionOccurs() public function testRetrieveUserReturnsUserFromTokenOnReauthentication() { - $userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock(); + $userProvider = $this->createMock(UserProviderInterface::class); $userProvider->expects($this->never()) ->method('loadUserByUsername') ; - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $token = $this->getSupportedToken(); $token->expects($this->once()) ->method('getUser') ->willReturn($user) ; - $provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(), 'key', $this->getMockBuilder(\Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface::class)->getMock()); + $provider = new DaoAuthenticationProvider($userProvider, $this->createMock(UserCheckerInterface::class), 'key', $this->createMock(EncoderFactoryInterface::class)); $reflection = new \ReflectionMethod($provider, 'retrieveUser'); $reflection->setAccessible(true); $result = $reflection->invoke($provider, null, $token); @@ -88,15 +95,15 @@ public function testRetrieveUserReturnsUserFromTokenOnReauthentication() public function testRetrieveUser() { - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); - $userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock(); + $userProvider = $this->createMock(UserProviderInterface::class); $userProvider->expects($this->once()) ->method('loadUserByUsername') ->willReturn($user) ; - $provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(), 'key', $this->getMockBuilder(\Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface::class)->getMock()); + $provider = new DaoAuthenticationProvider($userProvider, $this->createMock(UserCheckerInterface::class), 'key', $this->createMock(EncoderFactoryInterface::class)); $method = new \ReflectionMethod($provider, 'retrieveUser'); $method->setAccessible(true); @@ -105,8 +112,8 @@ public function testRetrieveUser() public function testCheckAuthenticationWhenCredentialsAreEmpty() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); - $encoder = $this->getMockBuilder(\Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface::class)->getMock(); + $this->expectException(BadCredentialsException::class); + $encoder = $this->createMock(PasswordEncoderInterface::class); $encoder ->expects($this->never()) ->method('isPasswordValid') @@ -125,14 +132,14 @@ public function testCheckAuthenticationWhenCredentialsAreEmpty() $method->invoke( $provider, - $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(), + $this->createMock(UserInterface::class), $token ); } public function testCheckAuthenticationWhenCredentialsAre0() { - $encoder = $this->getMockBuilder(\Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface::class)->getMock(); + $encoder = $this->createMock(PasswordEncoderInterface::class); $encoder ->expects($this->once()) ->method('isPasswordValid') @@ -159,8 +166,8 @@ public function testCheckAuthenticationWhenCredentialsAre0() public function testCheckAuthenticationWhenCredentialsAreNotValid() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); - $encoder = $this->getMockBuilder(\Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface::class)->getMock(); + $this->expectException(BadCredentialsException::class); + $encoder = $this->createMock(PasswordEncoderInterface::class); $encoder->expects($this->once()) ->method('isPasswordValid') ->willReturn(false) @@ -181,8 +188,8 @@ public function testCheckAuthenticationWhenCredentialsAreNotValid() public function testCheckAuthenticationDoesNotReauthenticateWhenPasswordHasChanged() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $this->expectException(BadCredentialsException::class); + $user = $this->createMock(UserInterface::class); $user->expects($this->once()) ->method('getPassword') ->willReturn('foo') @@ -193,7 +200,7 @@ public function testCheckAuthenticationDoesNotReauthenticateWhenPasswordHasChang ->method('getUser') ->willReturn($user); - $dbUser = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $dbUser = $this->createMock(UserInterface::class); $dbUser->expects($this->once()) ->method('getPassword') ->willReturn('newFoo') @@ -207,7 +214,7 @@ public function testCheckAuthenticationDoesNotReauthenticateWhenPasswordHasChang public function testCheckAuthenticationWhenTokenNeedsReauthenticationWorksWithoutOriginalCredentials() { - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user->expects($this->once()) ->method('getPassword') ->willReturn('foo') @@ -218,7 +225,7 @@ public function testCheckAuthenticationWhenTokenNeedsReauthenticationWorksWithou ->method('getUser') ->willReturn($user); - $dbUser = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $dbUser = $this->createMock(UserInterface::class); $dbUser->expects($this->once()) ->method('getPassword') ->willReturn('foo') @@ -232,7 +239,7 @@ public function testCheckAuthenticationWhenTokenNeedsReauthenticationWorksWithou public function testCheckAuthentication() { - $encoder = $this->getMockBuilder(\Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface::class)->getMock(); + $encoder = $this->createMock(PasswordEncoderInterface::class); $encoder->expects($this->once()) ->method('isPasswordValid') ->willReturn(true) @@ -255,7 +262,7 @@ public function testPasswordUpgrades() { $user = new User('user', 'pwd'); - $encoder = $this->getMockBuilder(TestPasswordEncoderInterface::class)->getMock(); + $encoder = $this->createMock(TestPasswordEncoderInterface::class); $encoder->expects($this->once()) ->method('isPasswordValid') ->willReturn(true) @@ -291,7 +298,7 @@ public function testPasswordUpgrades() protected function getSupportedToken() { - $mock = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::class)->setMethods(['getCredentials', 'getUser', 'getProviderKey'])->disableOriginalConstructor()->getMock(); + $mock = $this->getMockBuilder(UsernamePasswordToken::class)->setMethods(['getCredentials', 'getUser', 'getProviderKey'])->disableOriginalConstructor()->getMock(); $mock ->expects($this->any()) ->method('getProviderKey') @@ -303,7 +310,7 @@ protected function getSupportedToken() protected function getProvider($user = null, $userChecker = null, $passwordEncoder = null) { - $userProvider = $this->getMockBuilder(PasswordUpgraderProvider::class)->getMock(); + $userProvider = $this->createMock(PasswordUpgraderProvider::class); if (null !== $user) { $userProvider->expects($this->once()) ->method('loadUserByUsername') @@ -312,14 +319,14 @@ protected function getProvider($user = null, $userChecker = null, $passwordEncod } if (null === $userChecker) { - $userChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); } if (null === $passwordEncoder) { $passwordEncoder = new PlaintextPasswordEncoder(); } - $encoderFactory = $this->getMockBuilder(\Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface::class)->getMock(); + $encoderFactory = $this->createMock(EncoderFactoryInterface::class); $encoderFactory ->expects($this->any()) ->method('getEncoder') diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/LdapBindAuthenticationProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/LdapBindAuthenticationProviderTest.php index e3f0d72134de..0605df44e03c 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/LdapBindAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/LdapBindAuthenticationProviderTest.php @@ -19,6 +19,7 @@ use Symfony\Component\Ldap\LdapInterface; use Symfony\Component\Security\Core\Authentication\Provider\LdapBindAuthenticationProvider; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; +use Symfony\Component\Security\Core\Exception\BadCredentialsException; use Symfony\Component\Security\Core\User\User; use Symfony\Component\Security\Core\User\UserCheckerInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; @@ -30,11 +31,11 @@ class LdapBindAuthenticationProviderTest extends TestCase { public function testEmptyPasswordShouldThrowAnException() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $this->expectExceptionMessage('The presented password must not be empty.'); - $userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock(); - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); - $userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock(); + $userProvider = $this->createMock(UserProviderInterface::class); + $ldap = $this->createMock(LdapInterface::class); + $userChecker = $this->createMock(UserCheckerInterface::class); $provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap); $reflection = new \ReflectionMethod($provider, 'checkAuthentication'); @@ -45,11 +46,11 @@ public function testEmptyPasswordShouldThrowAnException() public function testNullPasswordShouldThrowAnException() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $this->expectExceptionMessage('The presented password must not be empty.'); - $userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock(); - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); - $userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock(); + $userProvider = $this->createMock(UserProviderInterface::class); + $ldap = $this->createMock(LdapInterface::class); + $userChecker = $this->createMock(UserCheckerInterface::class); $provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap); $reflection = new \ReflectionMethod($provider, 'checkAuthentication'); @@ -60,16 +61,16 @@ public function testNullPasswordShouldThrowAnException() public function testBindFailureShouldThrowAnException() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $this->expectExceptionMessage('The presented password is invalid.'); - $userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock(); - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $userProvider = $this->createMock(UserProviderInterface::class); + $ldap = $this->createMock(LdapInterface::class); $ldap ->expects($this->once()) ->method('bind') ->willThrowException(new ConnectionException()) ; - $userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); $provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap); $reflection = new \ReflectionMethod($provider, 'checkAuthentication'); @@ -80,15 +81,15 @@ public function testBindFailureShouldThrowAnException() public function testRetrieveUser() { - $userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock(); + $userProvider = $this->createMock(UserProviderInterface::class); $userProvider ->expects($this->once()) ->method('loadUserByUsername') ->with('foo') ; - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $ldap = $this->createMock(LdapInterface::class); - $userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); $provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap); $reflection = new \ReflectionMethod($provider, 'retrieveUser'); @@ -99,18 +100,18 @@ public function testRetrieveUser() public function testQueryForDn() { - $userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock(); + $userProvider = $this->createMock(UserProviderInterface::class); $collection = new \ArrayIterator([new Entry('')]); - $query = $this->getMockBuilder(QueryInterface::class)->getMock(); + $query = $this->createMock(QueryInterface::class); $query ->expects($this->once()) ->method('execute') ->willReturn($collection) ; - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $ldap = $this->createMock(LdapInterface::class); $ldap ->method('bind') ->withConsecutive( @@ -128,7 +129,7 @@ public function testQueryForDn() ->with('{username}', 'foobar') ->willReturn($query) ; - $userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); $provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap, '{username}', true, 'elsa', 'test1234A$'); $provider->setQueryString('{username}bar'); @@ -140,18 +141,18 @@ public function testQueryForDn() public function testQueryWithUserForDn() { - $userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock(); + $userProvider = $this->createMock(UserProviderInterface::class); $collection = new \ArrayIterator([new Entry('')]); - $query = $this->getMockBuilder(QueryInterface::class)->getMock(); + $query = $this->createMock(QueryInterface::class); $query ->expects($this->once()) ->method('execute') ->willReturn($collection) ; - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $ldap = $this->createMock(LdapInterface::class); $ldap ->method('bind') ->withConsecutive( @@ -170,7 +171,7 @@ public function testQueryWithUserForDn() ->willReturn($query) ; - $userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); $provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap, '{username}', true, 'elsa', 'test1234A$'); $provider->setQueryString('{username}bar'); @@ -182,20 +183,20 @@ public function testQueryWithUserForDn() public function testEmptyQueryResultShouldThrowAnException() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $this->expectExceptionMessage('The presented username is invalid.'); - $userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock(); + $userProvider = $this->createMock(UserProviderInterface::class); - $collection = $this->getMockBuilder(CollectionInterface::class)->getMock(); + $collection = $this->createMock(CollectionInterface::class); - $query = $this->getMockBuilder(QueryInterface::class)->getMock(); + $query = $this->createMock(QueryInterface::class); $query ->expects($this->once()) ->method('execute') ->willReturn($collection) ; - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $ldap = $this->createMock(LdapInterface::class); $ldap ->method('bind') ->withConsecutive( @@ -206,7 +207,7 @@ public function testEmptyQueryResultShouldThrowAnException() ->method('query') ->willReturn($query) ; - $userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); $provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap, '{username}', true, 'elsa', 'test1234A$'); $provider->setQueryString('{username}bar'); diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.php index 0438a9dfea34..6527bae618f9 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.php @@ -13,7 +13,13 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Authentication\Provider\PreAuthenticatedAuthenticationProvider; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; +use Symfony\Component\Security\Core\Exception\AuthenticationException; +use Symfony\Component\Security\Core\Exception\BadCredentialsException; use Symfony\Component\Security\Core\Exception\LockedException; +use Symfony\Component\Security\Core\User\UserCheckerInterface; +use Symfony\Component\Security\Core\User\UserInterface; +use Symfony\Component\Security\Core\User\UserProviderInterface; class PreAuthenticatedAuthenticationProviderTest extends TestCase { @@ -22,12 +28,9 @@ public function testSupports() $provider = $this->getProvider(); $this->assertTrue($provider->supports($this->getSupportedToken())); - $this->assertFalse($provider->supports($this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock())); + $this->assertFalse($provider->supports($this->createMock(TokenInterface::class))); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken::class) - ->disableOriginalConstructor() - ->getMock() - ; + $token = $this->createMock(\Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken::class); $token ->expects($this->once()) ->method('getProviderKey') @@ -38,23 +41,23 @@ public function testSupports() public function testAuthenticateWhenTokenIsNotSupported() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AuthenticationException::class); + $this->expectException(AuthenticationException::class); $this->expectExceptionMessage('The token is not supported by this authentication provider.'); $provider = $this->getProvider(); - $provider->authenticate($this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()); + $provider->authenticate($this->createMock(TokenInterface::class)); } public function testAuthenticateWhenNoUserIsSet() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $provider = $this->getProvider(); $provider->authenticate($this->getSupportedToken('')); } public function testAuthenticate() { - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user ->expects($this->once()) ->method('getRoles') @@ -74,9 +77,9 @@ public function testAuthenticate() public function testAuthenticateWhenUserCheckerThrowsException() { $this->expectException(LockedException::class); - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); - $userChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); $userChecker->expects($this->once()) ->method('checkPostAuth') ->willThrowException(new LockedException()) @@ -116,7 +119,7 @@ protected function getSupportedToken($user = false, $credentials = false) protected function getProvider($user = null, $userChecker = null) { - $userProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserProviderInterface::class)->getMock(); + $userProvider = $this->createMock(UserProviderInterface::class); if (null !== $user) { $userProvider->expects($this->once()) ->method('loadUserByUsername') @@ -125,7 +128,7 @@ protected function getProvider($user = null, $userChecker = null) } if (null === $userChecker) { - $userChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); } return new PreAuthenticatedAuthenticationProvider($userProvider, $userChecker, 'key'); diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/RememberMeAuthenticationProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/RememberMeAuthenticationProviderTest.php index 7832a87a145d..96d62692d1bd 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/RememberMeAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/RememberMeAuthenticationProviderTest.php @@ -14,8 +14,14 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Authentication\Provider\RememberMeAuthenticationProvider; use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; +use Symfony\Component\Security\Core\Exception\AuthenticationException; +use Symfony\Component\Security\Core\Exception\BadCredentialsException; use Symfony\Component\Security\Core\Exception\DisabledException; +use Symfony\Component\Security\Core\Exception\LogicException; use Symfony\Component\Security\Core\User\User; +use Symfony\Component\Security\Core\User\UserCheckerInterface; +use Symfony\Component\Security\Core\User\UserInterface; class RememberMeAuthenticationProviderTest extends TestCase { @@ -24,23 +30,23 @@ public function testSupports() $provider = $this->getProvider(); $this->assertTrue($provider->supports($this->getSupportedToken())); - $this->assertFalse($provider->supports($this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock())); - $this->assertFalse($provider->supports($this->getMockBuilder(RememberMeToken::class)->disableOriginalConstructor()->getMock())); + $this->assertFalse($provider->supports($this->createMock(TokenInterface::class))); + $this->assertFalse($provider->supports($this->createMock(RememberMeToken::class))); } public function testAuthenticateWhenTokenIsNotSupported() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AuthenticationException::class); + $this->expectException(AuthenticationException::class); $this->expectExceptionMessage('The token is not supported by this authentication provider.'); $provider = $this->getProvider(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $provider->authenticate($token); } public function testAuthenticateWhenSecretsDoNotMatch() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $provider = $this->getProvider(null, 'secret1'); $token = $this->getSupportedToken(null, 'secret2'); @@ -49,7 +55,7 @@ public function testAuthenticateWhenSecretsDoNotMatch() public function testAuthenticateThrowsOnNonUserInterfaceInstance() { - $this->expectException(\Symfony\Component\Security\Core\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Method "Symfony\Component\Security\Core\Authentication\Token\RememberMeToken::getUser()" must return a "Symfony\Component\Security\Core\User\UserInterface" instance, "string" returned.'); $provider = $this->getProvider(); @@ -61,7 +67,7 @@ public function testAuthenticateThrowsOnNonUserInterfaceInstance() public function testAuthenticateWhenPreChecksFails() { $this->expectException(DisabledException::class); - $userChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); $userChecker->expects($this->once()) ->method('checkPreAuth') ->willThrowException(new DisabledException()); @@ -73,7 +79,7 @@ public function testAuthenticateWhenPreChecksFails() public function testAuthenticate() { - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user->expects($this->exactly(2)) ->method('getRoles') ->willReturn(['ROLE_FOO']); @@ -92,7 +98,7 @@ public function testAuthenticate() protected function getSupportedToken($user = null, $secret = 'test') { if (null === $user) { - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user ->expects($this->any()) ->method('getRoles') @@ -111,7 +117,7 @@ protected function getSupportedToken($user = null, $secret = 'test') protected function getProvider($userChecker = null, $key = 'test') { if (null === $userChecker) { - $userChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); } return new RememberMeAuthenticationProvider($userChecker, $key, 'foo'); diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/SimpleAuthenticationProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/SimpleAuthenticationProviderTest.php index f712bbcd1e2a..053f2e545126 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/SimpleAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/SimpleAuthenticationProviderTest.php @@ -13,9 +13,14 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Authentication\Provider\SimpleAuthenticationProvider; +use Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\DisabledException; use Symfony\Component\Security\Core\Exception\LockedException; use Symfony\Component\Security\Core\User\UserChecker; +use Symfony\Component\Security\Core\User\UserCheckerInterface; +use Symfony\Component\Security\Core\User\UserInterface; +use Symfony\Component\Security\Core\User\UserProviderInterface; /** * @group legacy @@ -25,19 +30,19 @@ class SimpleAuthenticationProviderTest extends TestCase public function testAuthenticateWhenPreChecksFails() { $this->expectException(DisabledException::class); - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $token->expects($this->any()) ->method('getUser') ->willReturn($user); - $userChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); $userChecker->expects($this->once()) ->method('checkPreAuth') ->willThrowException(new DisabledException()); - $authenticator = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface::class)->getMock(); + $authenticator = $this->createMock(SimpleAuthenticatorInterface::class); $authenticator->expects($this->once()) ->method('authenticateToken') ->willReturn($token); @@ -50,19 +55,19 @@ public function testAuthenticateWhenPreChecksFails() public function testAuthenticateWhenPostChecksFails() { $this->expectException(LockedException::class); - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $token->expects($this->any()) ->method('getUser') ->willReturn($user); - $userChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); $userChecker->expects($this->once()) ->method('checkPostAuth') ->willThrowException(new LockedException()); - $authenticator = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface::class)->getMock(); + $authenticator = $this->createMock(SimpleAuthenticatorInterface::class); $authenticator->expects($this->once()) ->method('authenticateToken') ->willReturn($token); @@ -74,11 +79,11 @@ public function testAuthenticateWhenPostChecksFails() public function testAuthenticateSkipsUserChecksForNonUserInterfaceObjects() { - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $token->expects($this->any()) ->method('getUser') ->willReturn('string-user'); - $authenticator = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface::class)->getMock(); + $authenticator = $this->createMock(SimpleAuthenticatorInterface::class); $authenticator->expects($this->once()) ->method('authenticateToken') ->willReturn($token); @@ -89,13 +94,13 @@ public function testAuthenticateSkipsUserChecksForNonUserInterfaceObjects() protected function getProvider($simpleAuthenticator = null, $userProvider = null, $userChecker = null, $key = 'test') { if (null === $userChecker) { - $userChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); } if (null === $simpleAuthenticator) { - $simpleAuthenticator = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface::class)->getMock(); + $simpleAuthenticator = $this->createMock(SimpleAuthenticatorInterface::class); } if (null === $userProvider) { - $userProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserProviderInterface::class)->getMock(); + $userProvider = $this->createMock(UserProviderInterface::class); } return new SimpleAuthenticationProvider($simpleAuthenticator, $userProvider, $key, $userChecker); diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/UserAuthenticationProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/UserAuthenticationProviderTest.php index 19d6a61a2519..1ce9b7914a57 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/UserAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/UserAuthenticationProviderTest.php @@ -12,12 +12,19 @@ namespace Symfony\Component\Security\Core\Tests\Authentication\Provider; use PHPUnit\Framework\TestCase; +use Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider; use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; +use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; use Symfony\Component\Security\Core\Exception\AccountExpiredException; +use Symfony\Component\Security\Core\Exception\AuthenticationException; +use Symfony\Component\Security\Core\Exception\AuthenticationServiceException; use Symfony\Component\Security\Core\Exception\BadCredentialsException; use Symfony\Component\Security\Core\Exception\CredentialsExpiredException; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\Role\SwitchUserRole; +use Symfony\Component\Security\Core\User\UserCheckerInterface; +use Symfony\Component\Security\Core\User\UserInterface; class UserAuthenticationProviderTest extends TestCase { @@ -26,16 +33,16 @@ public function testSupports() $provider = $this->getProvider(); $this->assertTrue($provider->supports($this->getSupportedToken())); - $this->assertFalse($provider->supports($this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock())); + $this->assertFalse($provider->supports($this->createMock(TokenInterface::class))); } public function testAuthenticateWhenTokenIsNotSupported() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AuthenticationException::class); + $this->expectException(AuthenticationException::class); $this->expectExceptionMessage('The token is not supported by this authentication provider.'); $provider = $this->getProvider(); - $provider->authenticate($this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()); + $provider->authenticate($this->createMock(TokenInterface::class)); } public function testAuthenticateWhenUsernameIsNotFound() @@ -64,7 +71,7 @@ public function testAuthenticateWhenUsernameIsNotFoundAndHideIsTrue() public function testAuthenticateWhenProviderDoesNotReturnAnUserInterface() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AuthenticationServiceException::class); + $this->expectException(AuthenticationServiceException::class); $provider = $this->getProvider(false, true); $provider->expects($this->once()) ->method('retrieveUser') @@ -77,7 +84,7 @@ public function testAuthenticateWhenProviderDoesNotReturnAnUserInterface() public function testAuthenticateWhenPreChecksFails() { $this->expectException(CredentialsExpiredException::class); - $userChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); $userChecker->expects($this->once()) ->method('checkPreAuth') ->willThrowException(new CredentialsExpiredException()) @@ -86,7 +93,7 @@ public function testAuthenticateWhenPreChecksFails() $provider = $this->getProvider($userChecker); $provider->expects($this->once()) ->method('retrieveUser') - ->willReturn($this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock()) + ->willReturn($this->createMock(UserInterface::class)) ; $provider->authenticate($this->getSupportedToken()); @@ -95,7 +102,7 @@ public function testAuthenticateWhenPreChecksFails() public function testAuthenticateWhenPostChecksFails() { $this->expectException(AccountExpiredException::class); - $userChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); $userChecker->expects($this->once()) ->method('checkPostAuth') ->willThrowException(new AccountExpiredException()) @@ -104,7 +111,7 @@ public function testAuthenticateWhenPostChecksFails() $provider = $this->getProvider($userChecker); $provider->expects($this->once()) ->method('retrieveUser') - ->willReturn($this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock()) + ->willReturn($this->createMock(UserInterface::class)) ; $provider->authenticate($this->getSupportedToken()); @@ -117,7 +124,7 @@ public function testAuthenticateWhenPostCheckAuthenticationFails() $provider = $this->getProvider(); $provider->expects($this->once()) ->method('retrieveUser') - ->willReturn($this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock()) + ->willReturn($this->createMock(UserInterface::class)) ; $provider->expects($this->once()) ->method('checkAuthentication') @@ -134,7 +141,7 @@ public function testAuthenticateWhenPostCheckAuthenticationFailsWithHideFalse() $provider = $this->getProvider(false, false); $provider->expects($this->once()) ->method('retrieveUser') - ->willReturn($this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock()) + ->willReturn($this->createMock(UserInterface::class)) ; $provider->expects($this->once()) ->method('checkAuthentication') @@ -146,7 +153,7 @@ public function testAuthenticateWhenPostCheckAuthenticationFailsWithHideFalse() public function testAuthenticate() { - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user->expects($this->once()) ->method('getRoles') ->willReturn(['ROLE_FOO']) @@ -171,7 +178,7 @@ public function testAuthenticate() $authToken = $provider->authenticate($token); - $this->assertInstanceOf(\Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::class, $authToken); + $this->assertInstanceOf(UsernamePasswordToken::class, $authToken); $this->assertSame($user, $authToken->getUser()); $this->assertEquals(['ROLE_FOO'], $authToken->getRoleNames()); $this->assertEquals('foo', $authToken->getCredentials()); @@ -183,7 +190,7 @@ public function testAuthenticate() */ public function testAuthenticateWithPreservingRoleSwitchUserRole() { - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user->expects($this->once()) ->method('getRoles') ->willReturn(['ROLE_FOO']) @@ -201,7 +208,7 @@ public function testAuthenticateWithPreservingRoleSwitchUserRole() ->willReturn('foo') ; - $switchUserRole = new SwitchUserRole('foo', $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()); + $switchUserRole = new SwitchUserRole('foo', $this->createMock(TokenInterface::class)); $token->expects($this->once()) ->method('getRoles') ->willReturn([$switchUserRole]) @@ -209,7 +216,7 @@ public function testAuthenticateWithPreservingRoleSwitchUserRole() $authToken = $provider->authenticate($token); - $this->assertInstanceOf(\Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::class, $authToken); + $this->assertInstanceOf(UsernamePasswordToken::class, $authToken); $this->assertSame($user, $authToken->getUser()); $this->assertContains('ROLE_FOO', $authToken->getRoleNames()); $this->assertContains($switchUserRole, $authToken->getRoles()); @@ -219,7 +226,7 @@ public function testAuthenticateWithPreservingRoleSwitchUserRole() public function testAuthenticatePreservesOriginalToken() { - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user->expects($this->once()) ->method('getRoles') ->willReturn(['ROLE_FOO']) @@ -231,8 +238,8 @@ public function testAuthenticatePreservesOriginalToken() ->willReturn($user) ; - $originalToken = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); - $token = new SwitchUserToken($this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(), 'foo', 'key', [], $originalToken); + $originalToken = $this->createMock(TokenInterface::class); + $token = new SwitchUserToken($this->createMock(UserInterface::class), 'foo', 'key', [], $originalToken); $token->setAttributes(['foo' => 'bar']); $authToken = $provider->authenticate($token); @@ -247,7 +254,7 @@ public function testAuthenticatePreservesOriginalToken() protected function getSupportedToken() { - $mock = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::class)->setMethods(['getCredentials', 'getProviderKey', 'getRoles'])->disableOriginalConstructor()->getMock(); + $mock = $this->getMockBuilder(UsernamePasswordToken::class)->setMethods(['getCredentials', 'getProviderKey', 'getRoles'])->disableOriginalConstructor()->getMock(); $mock ->expects($this->any()) ->method('getProviderKey') @@ -262,9 +269,9 @@ protected function getSupportedToken() protected function getProvider($userChecker = false, $hide = true) { if (false === $userChecker) { - $userChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(); + $userChecker = $this->createMock(UserCheckerInterface::class); } - return $this->getMockForAbstractClass(\Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider::class, [$userChecker, 'key', $hide]); + return $this->getMockForAbstractClass(UserAuthenticationProvider::class, [$userChecker, 'key', $hide]); } } diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.php index ce686aac1fef..bbcbeb416d80 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Authentication\RememberMe\InMemoryTokenProvider; use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken; +use Symfony\Component\Security\Core\Exception\TokenNotFoundException; class InMemoryTokenProviderTest extends TestCase { @@ -29,7 +30,7 @@ public function testCreateNewToken() public function testLoadTokenBySeriesThrowsNotFoundException() { - $this->expectException(\Symfony\Component\Security\Core\Exception\TokenNotFoundException::class); + $this->expectException(TokenNotFoundException::class); $provider = new InMemoryTokenProvider(); $provider->loadTokenBySeries('foo'); } @@ -49,7 +50,7 @@ public function testUpdateToken() public function testDeleteToken() { - $this->expectException(\Symfony\Component\Security\Core\Exception\TokenNotFoundException::class); + $this->expectException(TokenNotFoundException::class); $provider = new InMemoryTokenProvider(); $token = new PersistentToken('foo', 'foo', 'foo', 'foo', new \DateTime()); diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Token/AbstractTokenTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Token/AbstractTokenTest.php index b409aef6af4c..17984b86d9cc 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Token/AbstractTokenTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Token/AbstractTokenTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Authentication\Token\AbstractToken; use Symfony\Component\Security\Core\Role\Role; +use Symfony\Component\Security\Core\User\AdvancedUserInterface; use Symfony\Component\Security\Core\User\User; use Symfony\Component\Security\Core\User\UserInterface; @@ -28,7 +29,7 @@ public function testGetUsername() $token->setUser(new TestUser('fabien')); $this->assertEquals('fabien', $token->getUsername()); - $user = $this->getMockBuilder(UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user->expects($this->once())->method('getUsername')->willReturn('fabien'); $token->setUser($user); $this->assertEquals('fabien', $token->getUsername()); @@ -38,7 +39,7 @@ public function testEraseCredentials() { $token = new ConcreteToken(['ROLE_FOO']); - $user = $this->getMockBuilder(UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user->expects($this->once())->method('eraseCredentials'); $token->setUser($user); @@ -151,7 +152,7 @@ public function testSetUser($user) public function getUsers() { - $user = $this->getMockBuilder(UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); return [ [$user], @@ -178,7 +179,7 @@ public function testSetUserSetsAuthenticatedToFalseWhenUserChanges($firstUser, $ public function getUserChanges() { - $user = $this->getMockBuilder(UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); return [ ['foo', 'bar'], @@ -212,8 +213,8 @@ public function testSetUserSetsAuthenticatedToFalseWhenUserChangesAdvancedUser($ public function getUserChangesAdvancedUser() { - $user = $this->getMockBuilder(UserInterface::class)->getMock(); - $advancedUser = $this->getMockBuilder(\Symfony\Component\Security\Core\User\AdvancedUserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); + $advancedUser = $this->createMock(AdvancedUserInterface::class); return [ ['foo', 'bar'], diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Token/RememberMeTokenTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Token/RememberMeTokenTest.php index ba634e5c7973..3d600accae6e 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Token/RememberMeTokenTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Token/RememberMeTokenTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken; +use Symfony\Component\Security\Core\User\UserInterface; class RememberMeTokenTest extends TestCase { @@ -40,7 +41,7 @@ public function testConstructorSecretCannotBeEmptyString() protected function getUser($roles = ['ROLE_FOO']) { - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user ->expects($this->any()) ->method('getRoles') diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Token/Storage/UsageTrackingTokenStorageTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Token/Storage/UsageTrackingTokenStorageTest.php index 3f353594f021..607ccc750480 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Token/Storage/UsageTrackingTokenStorageTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Token/Storage/UsageTrackingTokenStorageTest.php @@ -39,7 +39,7 @@ public function testGetSetToken() $trackingStorage = new UsageTrackingTokenStorage($tokenStorage, $sessionLocator); $this->assertNull($trackingStorage->getToken()); - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $trackingStorage->setToken($token); $this->assertSame($token, $trackingStorage->getToken()); diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.php index 40b978085c80..5e718564d98e 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Core\Tests\Authorization; use PHPUnit\Framework\TestCase; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\AccessDecisionManager; use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; @@ -28,7 +29,7 @@ public function testSetUnsupportedStrategy() */ public function testStrategies($strategy, $voters, $allowIfAllAbstainDecisions, $allowIfEqualGrantedDeniedDecisions, $expected) { - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $manager = new AccessDecisionManager($voters, $strategy, $allowIfAllAbstainDecisions, $allowIfEqualGrantedDeniedDecisions); $this->assertSame($expected, $manager->decide($token, ['ROLE_FOO'])); @@ -46,7 +47,7 @@ public function testLegacyStrategiesWith2Roles($token, $strategy, $voter, $expec public function getStrategiesWith2RolesTests() { - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); return [ [$token, 'affirmative', $this->getVoter(VoterInterface::ACCESS_DENIED), false], @@ -64,7 +65,7 @@ public function getStrategiesWith2RolesTests() protected function getVoterFor2Roles($token, $vote1, $vote2) { - $voter = $this->getMockBuilder(VoterInterface::class)->getMock(); + $voter = $this->createMock(VoterInterface::class); $voter->expects($this->any()) ->method('vote') ->willReturnMap([ @@ -129,7 +130,7 @@ protected function getVoters($grants, $denies, $abstains) protected function getVoter($vote) { - $voter = $this->getMockBuilder(VoterInterface::class)->getMock(); + $voter = $this->createMock(VoterInterface::class); $voter->expects($this->any()) ->method('vote') ->willReturn($vote); diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/AuthorizationCheckerTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/AuthorizationCheckerTest.php index 25286065fd46..05ac64f8fcbf 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/AuthorizationCheckerTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/AuthorizationCheckerTest.php @@ -12,9 +12,12 @@ namespace Symfony\Component\Security\Core\Tests\Authorization; use PHPUnit\Framework\TestCase; +use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; +use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationChecker; +use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException; class AuthorizationCheckerTest extends TestCase { @@ -25,8 +28,8 @@ class AuthorizationCheckerTest extends TestCase protected function setUp(): void { - $this->authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); - $this->accessDecisionManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface::class)->getMock(); + $this->authenticationManager = $this->createMock(AuthenticationManagerInterface::class); + $this->accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class); $this->tokenStorage = new TokenStorage(); $this->authorizationChecker = new AuthorizationChecker( @@ -69,7 +72,7 @@ public function testVoteAuthenticatesTokenIfNecessary() public function testVoteWithoutAuthenticationToken() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException::class); + $this->expectException(AuthenticationCredentialsNotFoundException::class); $this->authorizationChecker->isGranted('ROLE_FOO'); } diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/ExpressionLanguageTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/ExpressionLanguageTest.php index 2950d3feff7d..c47e43a742ac 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/ExpressionLanguageTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/ExpressionLanguageTest.php @@ -36,7 +36,7 @@ public function testIsAuthenticated($token, $expression, $result) $tokenStorage = new TokenStorage(); $tokenStorage->setToken($token); $accessDecisionManager = new AccessDecisionManager([new RoleVoter()]); - $authChecker = new AuthorizationChecker($tokenStorage, $this->getMockBuilder(AuthenticationManagerInterface::class)->getMock(), $accessDecisionManager); + $authChecker = new AuthorizationChecker($tokenStorage, $this->createMock(AuthenticationManagerInterface::class), $accessDecisionManager); $context = []; $context['trust_resolver'] = $trustResolver; diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/TraceableAccessDecisionManagerTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/TraceableAccessDecisionManagerTest.php index 4e66fac3cf26..d4f89396d337 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/TraceableAccessDecisionManagerTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/TraceableAccessDecisionManagerTest.php @@ -243,7 +243,7 @@ public function testAccessDecisionManagerCalledByVoter() return $vote; }); - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $sut->decide($token, ['attr1'], null); $sut->decide($token, ['attr2'], $obj = new \stdClass()); diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/AuthenticatedVoterTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/AuthenticatedVoterTest.php index 7e78a398fe7f..122caed8dbdc 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/AuthenticatedVoterTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/AuthenticatedVoterTest.php @@ -13,6 +13,9 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver; +use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken; +use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter; use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; @@ -55,11 +58,11 @@ public function getVoteTests() protected function getToken($authenticated) { if ('fully' === $authenticated) { - return $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + return $this->createMock(TokenInterface::class); } elseif ('remembered' === $authenticated) { - return $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\RememberMeToken::class)->setMethods(['setPersistent'])->disableOriginalConstructor()->getMock(); + return $this->getMockBuilder(RememberMeToken::class)->setMethods(['setPersistent'])->disableOriginalConstructor()->getMock(); } else { - return $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\AnonymousToken::class)->setConstructorArgs(['', ''])->getMock(); + return $this->getMockBuilder(AnonymousToken::class)->setConstructorArgs(['', ''])->getMock(); } } } diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/ExpressionVoterTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/ExpressionVoterTest.php index c979f6b039da..820a002f1196 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/ExpressionVoterTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/ExpressionVoterTest.php @@ -12,8 +12,12 @@ namespace Symfony\Component\Security\Core\Tests\Authorization\Voter; use PHPUnit\Framework\TestCase; +use Symfony\Component\ExpressionLanguage\Expression; +use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface; use Symfony\Component\Security\Core\Authentication\Token\AbstractToken; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; +use Symfony\Component\Security\Core\Authorization\ExpressionLanguage; use Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter; use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; use Symfony\Component\Security\Core\Role\Role; @@ -59,7 +63,7 @@ protected function getToken(array $roles, $tokenExpectsGetRoles = true) foreach ($roles as $i => $role) { $roles[$i] = new Role($role); } - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); if ($tokenExpectsGetRoles) { $token->expects($this->once()) @@ -72,7 +76,7 @@ protected function getToken(array $roles, $tokenExpectsGetRoles = true) protected function getTokenWithRoleNames(array $roles, $tokenExpectsGetRoles = true) { - $token = $this->getMockBuilder(AbstractToken::class)->getMock(); + $token = $this->createMock(AbstractToken::class); if ($tokenExpectsGetRoles) { $token->expects($this->once()) @@ -85,7 +89,7 @@ protected function getTokenWithRoleNames(array $roles, $tokenExpectsGetRoles = t protected function createExpressionLanguage($expressionLanguageExpectsEvaluate = true) { - $mock = $this->getMockBuilder(\Symfony\Component\Security\Core\Authorization\ExpressionLanguage::class)->getMock(); + $mock = $this->createMock(ExpressionLanguage::class); if ($expressionLanguageExpectsEvaluate) { $mock->expects($this->once()) @@ -98,18 +102,16 @@ protected function createExpressionLanguage($expressionLanguageExpectsEvaluate = protected function createTrustResolver() { - return $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface::class)->getMock(); + return $this->createMock(AuthenticationTrustResolverInterface::class); } protected function createAuthorizationChecker() { - return $this->getMockBuilder(AuthorizationCheckerInterface::class)->getMock(); + return $this->createMock(AuthorizationCheckerInterface::class); } protected function createExpression() { - return $this->getMockBuilder(\Symfony\Component\ExpressionLanguage\Expression::class) - ->disableOriginalConstructor() - ->getMock(); + return $this->createMock(Expression::class); } } diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/RoleVoterTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/RoleVoterTest.php index 90057ca0d543..d7d0f1f2dbd2 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/RoleVoterTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/RoleVoterTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Authentication\Token\AbstractToken; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\Voter\RoleVoter; use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; use Symfony\Component\Security\Core\Role\Role; @@ -80,7 +81,7 @@ protected function getToken(array $roles) foreach ($roles as $i => $role) { $roles[$i] = new Role($role); } - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $token->expects($this->once()) ->method('getRoles') ->willReturn($roles); @@ -90,7 +91,7 @@ protected function getToken(array $roles) protected function getTokenWithRoleNames(array $roles) { - $token = $this->getMockBuilder(AbstractToken::class)->getMock(); + $token = $this->createMock(AbstractToken::class); $token->expects($this->once()) ->method('getRoleNames') ->willReturn($roles); diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/VoterTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/VoterTest.php index 42ae1c63fbda..bf660073fe0e 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/VoterTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/VoterTest.php @@ -22,7 +22,7 @@ class VoterTest extends TestCase protected function setUp(): void { - $this->token = $this->getMockBuilder(TokenInterface::class)->getMock(); + $this->token = $this->createMock(TokenInterface::class); } public function getTests() diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/Argon2iPasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/Argon2iPasswordEncoderTest.php index 04ff8f9057c4..296b76ca42c3 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/Argon2iPasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/Argon2iPasswordEncoderTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Encoder\Argon2iPasswordEncoder; +use Symfony\Component\Security\Core\Exception\BadCredentialsException; /** * @author Zan Baldwin @@ -48,7 +49,7 @@ public function testValidation() public function testEncodePasswordLength() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $encoder = new Argon2iPasswordEncoder(); $encoder->encodePassword(str_repeat('a', 4097), 'salt'); } diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/BCryptPasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/BCryptPasswordEncoderTest.php index 9c4ed18c8a45..82c277b6bd4b 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/BCryptPasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/BCryptPasswordEncoderTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder; +use Symfony\Component\Security\Core\Exception\BadCredentialsException; /** * @author Elnur Abdurrakhimov @@ -69,7 +70,7 @@ public function testValidation() public function testEncodePasswordLength() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $encoder = new BCryptPasswordEncoder(self::VALID_COST); $encoder->encodePassword(str_repeat('a', 73), 'salt'); diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.php index 3df2f2112069..a6999991393c 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.php @@ -30,7 +30,7 @@ public function testGetEncoderWithMessageDigestEncoder() 'arguments' => ['sha512', true, 5], ]]); - $encoder = $factory->getEncoder($this->getMockBuilder(UserInterface::class)->getMock()); + $encoder = $factory->getEncoder($this->createMock(UserInterface::class)); $expectedEncoder = new MessageDigestPasswordEncoder('sha512', true, 5); $this->assertEquals($expectedEncoder->encodePassword('foo', 'moo'), $encoder->encodePassword('foo', 'moo')); @@ -42,7 +42,7 @@ public function testGetEncoderWithService() 'Symfony\Component\Security\Core\User\UserInterface' => new MessageDigestPasswordEncoder('sha1'), ]); - $encoder = $factory->getEncoder($this->getMockBuilder(UserInterface::class)->getMock()); + $encoder = $factory->getEncoder($this->createMock(UserInterface::class)); $expectedEncoder = new MessageDigestPasswordEncoder('sha1'); $this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', '')); diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/MessageDigestPasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/MessageDigestPasswordEncoderTest.php index 0e2942b18558..c2b514bb6b0a 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/MessageDigestPasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/MessageDigestPasswordEncoderTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder; +use Symfony\Component\Security\Core\Exception\BadCredentialsException; class MessageDigestPasswordEncoderTest extends TestCase { @@ -44,7 +45,7 @@ public function testEncodePasswordAlgorithmDoesNotExist() public function testEncodePasswordLength() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $encoder = new MessageDigestPasswordEncoder(); $encoder->encodePassword(str_repeat('a', 5000), 'salt'); diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/MigratingPasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/MigratingPasswordEncoderTest.php index 468c326f35aa..efa360ecb2cf 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/MigratingPasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/MigratingPasswordEncoderTest.php @@ -21,7 +21,7 @@ public function testValidation() { $bestEncoder = new NativePasswordEncoder(4, 12000, 4); - $extraEncoder = $this->getMockBuilder(TestPasswordEncoderInterface::class)->getMock(); + $extraEncoder = $this->createMock(TestPasswordEncoderInterface::class); $extraEncoder->expects($this->never())->method('encodePassword'); $extraEncoder->expects($this->never())->method('isPasswordValid'); $extraEncoder->expects($this->never())->method('needsRehash'); @@ -41,7 +41,7 @@ public function testFallback() { $bestEncoder = new NativePasswordEncoder(4, 12000, 4); - $extraEncoder1 = $this->getMockBuilder(TestPasswordEncoderInterface::class)->getMock(); + $extraEncoder1 = $this->createMock(TestPasswordEncoderInterface::class); $extraEncoder1->expects($this->any()) ->method('isPasswordValid') ->with('abc', 'foo', 'salt') @@ -51,7 +51,7 @@ public function testFallback() $this->assertTrue($encoder->isPasswordValid('abc', 'foo', 'salt')); - $extraEncoder2 = $this->getMockBuilder(TestPasswordEncoderInterface::class)->getMock(); + $extraEncoder2 = $this->createMock(TestPasswordEncoderInterface::class); $extraEncoder2->expects($this->any()) ->method('isPasswordValid') ->willReturn(false); diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/Pbkdf2PasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/Pbkdf2PasswordEncoderTest.php index 82ed24e3f520..db274716bd83 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/Pbkdf2PasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/Pbkdf2PasswordEncoderTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Encoder\Pbkdf2PasswordEncoder; +use Symfony\Component\Security\Core\Exception\BadCredentialsException; class Pbkdf2PasswordEncoderTest extends TestCase { @@ -44,7 +45,7 @@ public function testEncodePasswordAlgorithmDoesNotExist() public function testEncodePasswordLength() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $encoder = new Pbkdf2PasswordEncoder('foobar'); $encoder->encodePassword(str_repeat('a', 5000), 'salt'); diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/PlaintextPasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/PlaintextPasswordEncoderTest.php index 40c038b65a28..fb5e674567d1 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/PlaintextPasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/PlaintextPasswordEncoderTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder; +use Symfony\Component\Security\Core\Exception\BadCredentialsException; class PlaintextPasswordEncoderTest extends TestCase { @@ -40,7 +41,7 @@ public function testEncodePassword() public function testEncodePasswordLength() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $encoder = new PlaintextPasswordEncoder(); $encoder->encodePassword(str_repeat('a', 5000), 'salt'); diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/SodiumPasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/SodiumPasswordEncoderTest.php index b2c5bd186b47..b4073a1cfba5 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/SodiumPasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/SodiumPasswordEncoderTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Encoder\SodiumPasswordEncoder; +use Symfony\Component\Security\Core\Exception\BadCredentialsException; class SodiumPasswordEncoderTest extends TestCase { @@ -49,7 +50,7 @@ public function testNonArgonValidation() public function testEncodePasswordLength() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $encoder = new SodiumPasswordEncoder(); $encoder->encodePassword(str_repeat('a', 4097), 'salt'); } diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/UserPasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/UserPasswordEncoderTest.php index 2c0a265f3f48..0d72919abc40 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/UserPasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/UserPasswordEncoderTest.php @@ -14,25 +14,27 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface; use Symfony\Component\Security\Core\Encoder\NativePasswordEncoder; +use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface; use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder; use Symfony\Component\Security\Core\User\User; +use Symfony\Component\Security\Core\User\UserInterface; class UserPasswordEncoderTest extends TestCase { public function testEncodePassword() { - $userMock = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $userMock = $this->createMock(UserInterface::class); $userMock->expects($this->any()) ->method('getSalt') ->willReturn('userSalt'); - $mockEncoder = $this->getMockBuilder(\Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface::class)->getMock(); + $mockEncoder = $this->createMock(PasswordEncoderInterface::class); $mockEncoder->expects($this->any()) ->method('encodePassword') ->with($this->equalTo('plainPassword'), $this->equalTo('userSalt')) ->willReturn('encodedPassword'); - $mockEncoderFactory = $this->getMockBuilder(EncoderFactoryInterface::class)->getMock(); + $mockEncoderFactory = $this->createMock(EncoderFactoryInterface::class); $mockEncoderFactory->expects($this->any()) ->method('getEncoder') ->with($this->equalTo($userMock)) @@ -46,7 +48,7 @@ public function testEncodePassword() public function testIsPasswordValid() { - $userMock = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $userMock = $this->createMock(UserInterface::class); $userMock->expects($this->any()) ->method('getSalt') ->willReturn('userSalt'); @@ -54,13 +56,13 @@ public function testIsPasswordValid() ->method('getPassword') ->willReturn('encodedPassword'); - $mockEncoder = $this->getMockBuilder(\Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface::class)->getMock(); + $mockEncoder = $this->createMock(PasswordEncoderInterface::class); $mockEncoder->expects($this->any()) ->method('isPasswordValid') ->with($this->equalTo('encodedPassword'), $this->equalTo('plainPassword'), $this->equalTo('userSalt')) ->willReturn(true); - $mockEncoderFactory = $this->getMockBuilder(EncoderFactoryInterface::class)->getMock(); + $mockEncoderFactory = $this->createMock(EncoderFactoryInterface::class); $mockEncoderFactory->expects($this->any()) ->method('getEncoder') ->with($this->equalTo($userMock)) @@ -77,7 +79,7 @@ public function testNeedsRehash() $user = new User('username', null); $encoder = new NativePasswordEncoder(4, 20000, 4); - $mockEncoderFactory = $this->getMockBuilder(EncoderFactoryInterface::class)->getMock(); + $mockEncoderFactory = $this->createMock(EncoderFactoryInterface::class); $mockEncoderFactory->expects($this->any()) ->method('getEncoder') ->with($user) diff --git a/src/Symfony/Component/Security/Core/Tests/Role/SwitchUserRoleTest.php b/src/Symfony/Component/Security/Core/Tests/Role/SwitchUserRoleTest.php index 3d7ad26dea91..f84afdf0989b 100644 --- a/src/Symfony/Component/Security/Core/Tests/Role/SwitchUserRoleTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Role/SwitchUserRoleTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Core\Tests\Role; use PHPUnit\Framework\TestCase; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Role\SwitchUserRole; /** @@ -21,14 +22,14 @@ class SwitchUserRoleTest extends TestCase { public function testGetSource() { - $role = new SwitchUserRole('FOO', $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()); + $role = new SwitchUserRole('FOO', $token = $this->createMock(TokenInterface::class)); $this->assertSame($token, $role->getSource()); } public function testGetRole() { - $role = new SwitchUserRole('FOO', $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()); + $role = new SwitchUserRole('FOO', $this->createMock(TokenInterface::class)); $this->assertEquals('FOO', $role->getRole()); } diff --git a/src/Symfony/Component/Security/Core/Tests/SecurityTest.php b/src/Symfony/Component/Security/Core/Tests/SecurityTest.php index 49f6f8dbe3c3..efc480f82f24 100644 --- a/src/Symfony/Component/Security/Core/Tests/SecurityTest.php +++ b/src/Symfony/Component/Security/Core/Tests/SecurityTest.php @@ -25,7 +25,7 @@ class SecurityTest extends TestCase public function testGetToken() { $token = new UsernamePasswordToken('foo', 'bar', 'provider'); - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage->expects($this->once()) ->method('getToken') @@ -42,11 +42,11 @@ public function testGetToken() */ public function testGetUser($userInToken, $expectedUser) { - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $token->expects($this->any()) ->method('getUser') ->willReturn($userInToken); - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage->expects($this->once()) ->method('getToken') @@ -76,11 +76,11 @@ public function getUserTests() */ public function testGetUserLegacy() { - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $token->expects($this->any()) ->method('getUser') ->willReturn($user = new StringishUser()); - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage->expects($this->once()) ->method('getToken') @@ -94,7 +94,7 @@ public function testGetUserLegacy() public function testIsGranted() { - $authorizationChecker = $this->getMockBuilder(AuthorizationCheckerInterface::class)->getMock(); + $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class); $authorizationChecker->expects($this->once()) ->method('isGranted') @@ -109,7 +109,7 @@ public function testIsGranted() private function createContainer($serviceId, $serviceObject) { - $container = $this->getMockBuilder(ContainerInterface::class)->getMock(); + $container = $this->createMock(ContainerInterface::class); $container->expects($this->atLeastOnce()) ->method('get') diff --git a/src/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.php b/src/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.php index 29440ce1599c..cb172d2b5138 100644 --- a/src/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.php @@ -17,6 +17,8 @@ use Symfony\Component\Security\Core\User\ChainUserProvider; use Symfony\Component\Security\Core\User\PasswordUpgraderInterface; use Symfony\Component\Security\Core\User\User; +use Symfony\Component\Security\Core\User\UserInterface; +use Symfony\Component\Security\Core\User\UserProviderInterface; class ChainUserProviderTest extends TestCase { @@ -249,14 +251,14 @@ public function testPasswordUpgrades() { $user = new User('user', 'pwd'); - $provider1 = $this->getMockBuilder(PasswordUpgraderInterface::class)->getMock(); + $provider1 = $this->createMock(PasswordUpgraderInterface::class); $provider1 ->expects($this->once()) ->method('upgradePassword') ->willThrowException(new UnsupportedUserException('unsupported')) ; - $provider2 = $this->getMockBuilder(PasswordUpgraderInterface::class)->getMock(); + $provider2 = $this->createMock(PasswordUpgraderInterface::class); $provider2 ->expects($this->once()) ->method('upgradePassword') @@ -269,11 +271,11 @@ public function testPasswordUpgrades() protected function getAccount() { - return $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + return $this->createMock(UserInterface::class); } protected function getProvider() { - return $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserProviderInterface::class)->getMock(); + return $this->createMock(UserProviderInterface::class); } } diff --git a/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserProviderTest.php b/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserProviderTest.php index ad2b03828771..4f1438ad8d26 100644 --- a/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserProviderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Core\Tests\User; use PHPUnit\Framework\TestCase; +use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\User\InMemoryUserProvider; use Symfony\Component\Security\Core\User\User; @@ -70,7 +71,7 @@ public function testCreateUserAlreadyExist() public function testLoadUserByUsernameDoesNotExist() { - $this->expectException(\Symfony\Component\Security\Core\Exception\UsernameNotFoundException::class); + $this->expectException(UsernameNotFoundException::class); $provider = new InMemoryUserProvider(); $provider->loadUserByUsername('fabien'); } diff --git a/src/Symfony/Component/Security/Core/Tests/User/LdapUserProviderTest.php b/src/Symfony/Component/Security/Core/Tests/User/LdapUserProviderTest.php index f4d609e29966..8c04e1b36fc0 100644 --- a/src/Symfony/Component/Security/Core/Tests/User/LdapUserProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/User/LdapUserProviderTest.php @@ -17,6 +17,8 @@ use Symfony\Component\Ldap\Entry; use Symfony\Component\Ldap\Exception\ConnectionException; use Symfony\Component\Ldap\LdapInterface; +use Symfony\Component\Security\Core\Exception\InvalidArgumentException; +use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\User\LdapUserProvider; /** @@ -27,8 +29,8 @@ class LdapUserProviderTest extends TestCase { public function testLoadUserByUsernameFailsIfCantConnectToLdap() { - $this->expectException(\Symfony\Component\Security\Core\Exception\UsernameNotFoundException::class); - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $this->expectException(UsernameNotFoundException::class); + $ldap = $this->createMock(LdapInterface::class); $ldap ->expects($this->once()) ->method('bind') @@ -41,9 +43,9 @@ public function testLoadUserByUsernameFailsIfCantConnectToLdap() public function testLoadUserByUsernameFailsIfNoLdapEntries() { - $this->expectException(\Symfony\Component\Security\Core\Exception\UsernameNotFoundException::class); - $result = $this->getMockBuilder(CollectionInterface::class)->getMock(); - $query = $this->getMockBuilder(QueryInterface::class)->getMock(); + $this->expectException(UsernameNotFoundException::class); + $result = $this->createMock(CollectionInterface::class); + $query = $this->createMock(QueryInterface::class); $query ->expects($this->once()) ->method('execute') @@ -54,7 +56,7 @@ public function testLoadUserByUsernameFailsIfNoLdapEntries() ->method('count') ->willReturn(0) ; - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $ldap = $this->createMock(LdapInterface::class); $ldap ->expects($this->once()) ->method('escape') @@ -72,9 +74,9 @@ public function testLoadUserByUsernameFailsIfNoLdapEntries() public function testLoadUserByUsernameFailsIfMoreThanOneLdapEntry() { - $this->expectException(\Symfony\Component\Security\Core\Exception\UsernameNotFoundException::class); - $result = $this->getMockBuilder(CollectionInterface::class)->getMock(); - $query = $this->getMockBuilder(QueryInterface::class)->getMock(); + $this->expectException(UsernameNotFoundException::class); + $result = $this->createMock(CollectionInterface::class); + $query = $this->createMock(QueryInterface::class); $query ->expects($this->once()) ->method('execute') @@ -85,7 +87,7 @@ public function testLoadUserByUsernameFailsIfMoreThanOneLdapEntry() ->method('count') ->willReturn(2) ; - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $ldap = $this->createMock(LdapInterface::class); $ldap ->expects($this->once()) ->method('escape') @@ -103,15 +105,15 @@ public function testLoadUserByUsernameFailsIfMoreThanOneLdapEntry() public function testLoadUserByUsernameFailsIfMoreThanOneLdapPasswordsInEntry() { - $this->expectException(\Symfony\Component\Security\Core\Exception\InvalidArgumentException::class); - $result = $this->getMockBuilder(CollectionInterface::class)->getMock(); - $query = $this->getMockBuilder(QueryInterface::class)->getMock(); + $this->expectException(InvalidArgumentException::class); + $result = $this->createMock(CollectionInterface::class); + $query = $this->createMock(QueryInterface::class); $query ->expects($this->once()) ->method('execute') ->willReturn($result) ; - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $ldap = $this->createMock(LdapInterface::class); $result ->expects($this->once()) ->method('offsetGet') @@ -147,14 +149,14 @@ public function testLoadUserByUsernameFailsIfMoreThanOneLdapPasswordsInEntry() public function testLoadUserByUsernameShouldNotFailIfEntryHasNoUidKeyAttribute() { - $result = $this->getMockBuilder(CollectionInterface::class)->getMock(); - $query = $this->getMockBuilder(QueryInterface::class)->getMock(); + $result = $this->createMock(CollectionInterface::class); + $query = $this->createMock(QueryInterface::class); $query ->expects($this->once()) ->method('execute') ->willReturn($result) ; - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $ldap = $this->createMock(LdapInterface::class); $result ->expects($this->once()) ->method('offsetGet') @@ -186,15 +188,15 @@ public function testLoadUserByUsernameShouldNotFailIfEntryHasNoUidKeyAttribute() public function testLoadUserByUsernameFailsIfEntryHasNoPasswordAttribute() { - $this->expectException(\Symfony\Component\Security\Core\Exception\InvalidArgumentException::class); - $result = $this->getMockBuilder(CollectionInterface::class)->getMock(); - $query = $this->getMockBuilder(QueryInterface::class)->getMock(); + $this->expectException(InvalidArgumentException::class); + $result = $this->createMock(CollectionInterface::class); + $query = $this->createMock(QueryInterface::class); $query ->expects($this->once()) ->method('execute') ->willReturn($result) ; - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $ldap = $this->createMock(LdapInterface::class); $result ->expects($this->once()) ->method('offsetGet') @@ -229,14 +231,14 @@ public function testLoadUserByUsernameFailsIfEntryHasNoPasswordAttribute() public function testLoadUserByUsernameIsSuccessfulWithoutPasswordAttribute() { - $result = $this->getMockBuilder(CollectionInterface::class)->getMock(); - $query = $this->getMockBuilder(QueryInterface::class)->getMock(); + $result = $this->createMock(CollectionInterface::class); + $query = $this->createMock(QueryInterface::class); $query ->expects($this->once()) ->method('execute') ->willReturn($result) ; - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $ldap = $this->createMock(LdapInterface::class); $result ->expects($this->once()) ->method('offsetGet') @@ -271,14 +273,14 @@ public function testLoadUserByUsernameIsSuccessfulWithoutPasswordAttribute() public function testLoadUserByUsernameIsSuccessfulWithoutPasswordAttributeAndWrongCase() { - $result = $this->getMockBuilder(CollectionInterface::class)->getMock(); - $query = $this->getMockBuilder(QueryInterface::class)->getMock(); + $result = $this->createMock(CollectionInterface::class); + $query = $this->createMock(QueryInterface::class); $query ->expects($this->once()) ->method('execute') ->willReturn($result) ; - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $ldap = $this->createMock(LdapInterface::class); $result ->expects($this->once()) ->method('offsetGet') @@ -310,14 +312,14 @@ public function testLoadUserByUsernameIsSuccessfulWithoutPasswordAttributeAndWro public function testLoadUserByUsernameIsSuccessfulWithPasswordAttribute() { - $result = $this->getMockBuilder(CollectionInterface::class)->getMock(); - $query = $this->getMockBuilder(QueryInterface::class)->getMock(); + $result = $this->createMock(CollectionInterface::class); + $query = $this->createMock(QueryInterface::class); $query ->expects($this->once()) ->method('execute') ->willReturn($result) ; - $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); + $ldap = $this->createMock(LdapInterface::class); $result ->expects($this->once()) ->method('offsetGet') diff --git a/src/Symfony/Component/Security/Core/Tests/User/UserCheckerTest.php b/src/Symfony/Component/Security/Core/Tests/User/UserCheckerTest.php index a618034ea86a..8c353f94f8eb 100644 --- a/src/Symfony/Component/Security/Core/Tests/User/UserCheckerTest.php +++ b/src/Symfony/Component/Security/Core/Tests/User/UserCheckerTest.php @@ -12,8 +12,14 @@ namespace Symfony\Component\Security\Core\Tests\User; use PHPUnit\Framework\TestCase; +use Symfony\Component\Security\Core\Exception\AccountExpiredException; +use Symfony\Component\Security\Core\Exception\CredentialsExpiredException; +use Symfony\Component\Security\Core\Exception\DisabledException; +use Symfony\Component\Security\Core\Exception\LockedException; +use Symfony\Component\Security\Core\User\AdvancedUserInterface; use Symfony\Component\Security\Core\User\User; use Symfony\Component\Security\Core\User\UserChecker; +use Symfony\Component\Security\Core\User\UserInterface; class UserCheckerTest extends TestCase { @@ -21,7 +27,7 @@ public function testCheckPostAuthNotAdvancedUserInterface() { $checker = new UserChecker(); - $this->assertNull($checker->checkPostAuth($this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock())); + $this->assertNull($checker->checkPostAuth($this->createMock(UserInterface::class))); } public function testCheckPostAuthPass() @@ -38,7 +44,7 @@ public function testCheckPostAuthPassAdvancedUser() { $checker = new UserChecker(); - $account = $this->getMockBuilder(\Symfony\Component\Security\Core\User\AdvancedUserInterface::class)->getMock(); + $account = $this->createMock(AdvancedUserInterface::class); $account->expects($this->once())->method('isCredentialsNonExpired')->willReturn(true); $this->assertNull($checker->checkPostAuth($account)); @@ -46,7 +52,7 @@ public function testCheckPostAuthPassAdvancedUser() public function testCheckPostAuthCredentialsExpired() { - $this->expectException(\Symfony\Component\Security\Core\Exception\CredentialsExpiredException::class); + $this->expectException(CredentialsExpiredException::class); $checker = new UserChecker(); $checker->checkPostAuth(new User('John', 'password', [], true, true, false, true)); } @@ -57,10 +63,10 @@ public function testCheckPostAuthCredentialsExpired() */ public function testCheckPostAuthCredentialsExpiredAdvancedUser() { - $this->expectException(\Symfony\Component\Security\Core\Exception\CredentialsExpiredException::class); + $this->expectException(CredentialsExpiredException::class); $checker = new UserChecker(); - $account = $this->getMockBuilder(\Symfony\Component\Security\Core\User\AdvancedUserInterface::class)->getMock(); + $account = $this->createMock(AdvancedUserInterface::class); $account->expects($this->once())->method('isCredentialsNonExpired')->willReturn(false); $checker->checkPostAuth($account); @@ -74,7 +80,7 @@ public function testCheckPreAuthPassAdvancedUser() { $checker = new UserChecker(); - $account = $this->getMockBuilder(\Symfony\Component\Security\Core\User\AdvancedUserInterface::class)->getMock(); + $account = $this->createMock(AdvancedUserInterface::class); $account->expects($this->once())->method('isAccountNonLocked')->willReturn(true); $account->expects($this->once())->method('isEnabled')->willReturn(true); $account->expects($this->once())->method('isAccountNonExpired')->willReturn(true); @@ -84,7 +90,7 @@ public function testCheckPreAuthPassAdvancedUser() public function testCheckPreAuthAccountLocked() { - $this->expectException(\Symfony\Component\Security\Core\Exception\LockedException::class); + $this->expectException(LockedException::class); $checker = new UserChecker(); $checker->checkPreAuth(new User('John', 'password', [], true, true, false, false)); } @@ -95,10 +101,10 @@ public function testCheckPreAuthAccountLocked() */ public function testCheckPreAuthAccountLockedAdvancedUser() { - $this->expectException(\Symfony\Component\Security\Core\Exception\LockedException::class); + $this->expectException(LockedException::class); $checker = new UserChecker(); - $account = $this->getMockBuilder(\Symfony\Component\Security\Core\User\AdvancedUserInterface::class)->getMock(); + $account = $this->createMock(AdvancedUserInterface::class); $account->expects($this->once())->method('isAccountNonLocked')->willReturn(false); $checker->checkPreAuth($account); @@ -106,7 +112,7 @@ public function testCheckPreAuthAccountLockedAdvancedUser() public function testCheckPreAuthDisabled() { - $this->expectException(\Symfony\Component\Security\Core\Exception\DisabledException::class); + $this->expectException(DisabledException::class); $checker = new UserChecker(); $checker->checkPreAuth(new User('John', 'password', [], false, true, false, true)); } @@ -117,10 +123,10 @@ public function testCheckPreAuthDisabled() */ public function testCheckPreAuthDisabledAdvancedUser() { - $this->expectException(\Symfony\Component\Security\Core\Exception\DisabledException::class); + $this->expectException(DisabledException::class); $checker = new UserChecker(); - $account = $this->getMockBuilder(\Symfony\Component\Security\Core\User\AdvancedUserInterface::class)->getMock(); + $account = $this->createMock(AdvancedUserInterface::class); $account->expects($this->once())->method('isAccountNonLocked')->willReturn(true); $account->expects($this->once())->method('isEnabled')->willReturn(false); @@ -129,7 +135,7 @@ public function testCheckPreAuthDisabledAdvancedUser() public function testCheckPreAuthAccountExpired() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AccountExpiredException::class); + $this->expectException(AccountExpiredException::class); $checker = new UserChecker(); $checker->checkPreAuth(new User('John', 'password', [], true, false, true, true)); } @@ -140,10 +146,10 @@ public function testCheckPreAuthAccountExpired() */ public function testCheckPreAuthAccountExpiredAdvancedUser() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AccountExpiredException::class); + $this->expectException(AccountExpiredException::class); $checker = new UserChecker(); - $account = $this->getMockBuilder(\Symfony\Component\Security\Core\User\AdvancedUserInterface::class)->getMock(); + $account = $this->createMock(AdvancedUserInterface::class); $account->expects($this->once())->method('isAccountNonLocked')->willReturn(true); $account->expects($this->once())->method('isEnabled')->willReturn(true); $account->expects($this->once())->method('isAccountNonExpired')->willReturn(false); diff --git a/src/Symfony/Component/Security/Core/Tests/User/UserTest.php b/src/Symfony/Component/Security/Core/Tests/User/UserTest.php index 240e6ab4e906..21e0ac7717cf 100644 --- a/src/Symfony/Component/Security/Core/Tests/User/UserTest.php +++ b/src/Symfony/Component/Security/Core/Tests/User/UserTest.php @@ -130,6 +130,6 @@ public static function isEqualToData() public function testIsEqualToWithDifferentUser() { $user = new User('username', 'password'); - $this->assertFalse($user->isEqualTo($this->getMockBuilder(UserInterface::class)->getMock())); + $this->assertFalse($user->isEqualTo($this->createMock(UserInterface::class))); } } diff --git a/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php b/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php index 62989ebb69fb..7c2d93ada1b2 100644 --- a/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php @@ -11,11 +11,15 @@ namespace Symfony\Component\Security\Core\Tests\Validator\Constraints; +use Foo\Bar\User; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface; use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface; +use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\Validator\Constraints\UserPassword; use Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; /** @@ -114,8 +118,8 @@ public function emptyPasswordData() public function testUserIsNotValid() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); - $user = $this->getMockBuilder(\Foo\Bar\User::class)->getMock(); + $this->expectException(ConstraintDefinitionException::class); + $user = $this->createMock(User::class); $this->tokenStorage = $this->createTokenStorage($user); $this->validator = $this->createValidator(); @@ -126,7 +130,7 @@ public function testUserIsNotValid() protected function createUser() { - $mock = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $mock = $this->createMock(UserInterface::class); $mock ->expects($this->any()) @@ -145,12 +149,12 @@ protected function createUser() protected function createPasswordEncoder($isPasswordValid = true) { - return $this->getMockBuilder(PasswordEncoderInterface::class)->getMock(); + return $this->createMock(PasswordEncoderInterface::class); } protected function createEncoderFactory($encoder = null) { - $mock = $this->getMockBuilder(EncoderFactoryInterface::class)->getMock(); + $mock = $this->createMock(EncoderFactoryInterface::class); $mock ->expects($this->any()) @@ -165,7 +169,7 @@ protected function createTokenStorage($user = null) { $token = $this->createAuthenticationToken($user); - $mock = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); + $mock = $this->createMock(TokenStorageInterface::class); $mock ->expects($this->any()) ->method('getToken') @@ -177,7 +181,7 @@ protected function createTokenStorage($user = null) protected function createAuthenticationToken($user = null) { - $mock = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $mock = $this->createMock(TokenInterface::class); $mock ->expects($this->any()) ->method('getUser') diff --git a/src/Symfony/Component/Security/Csrf/Tests/CsrfTokenManagerTest.php b/src/Symfony/Component/Security/Csrf/Tests/CsrfTokenManagerTest.php index 772bcf171560..d51a7334bad7 100644 --- a/src/Symfony/Component/Security/Csrf/Tests/CsrfTokenManagerTest.php +++ b/src/Symfony/Component/Security/Csrf/Tests/CsrfTokenManagerTest.php @@ -16,6 +16,8 @@ use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Security\Csrf\CsrfToken; use Symfony\Component\Security\Csrf\CsrfTokenManager; +use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface; +use Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface; /** * @author Bernhard Schussek @@ -159,8 +161,8 @@ public function testRemoveToken($namespace, $manager, $storage) public function testNamespaced() { - $generator = $this->getMockBuilder(\Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface::class)->getMock(); - $storage = $this->getMockBuilder(\Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface::class)->getMock(); + $generator = $this->createMock(TokenGeneratorInterface::class); + $storage = $this->createMock(TokenStorageInterface::class); $requestStack = new RequestStack(); $requestStack->push(new Request([], [], [], [], [], ['HTTPS' => 'on'])); @@ -205,8 +207,8 @@ public function getManagerGeneratorAndStorage() private function getGeneratorAndStorage(): array { return [ - $this->getMockBuilder(\Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface::class)->getMock(), - $this->getMockBuilder(\Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface::class)->getMock(), + $this->createMock(TokenGeneratorInterface::class), + $this->createMock(TokenStorageInterface::class), ]; } diff --git a/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.php b/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.php index fadb87e6ab40..cde252af84de 100644 --- a/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.php +++ b/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Csrf\Tests\TokenStorage; use PHPUnit\Framework\TestCase; +use Symfony\Component\Security\Csrf\Exception\TokenNotFoundException; use Symfony\Component\Security\Csrf\TokenStorage\NativeSessionTokenStorage; /** @@ -88,7 +89,7 @@ public function testGetExistingToken() public function testGetNonExistingToken() { - $this->expectException(\Symfony\Component\Security\Csrf\Exception\TokenNotFoundException::class); + $this->expectException(TokenNotFoundException::class); $this->storage->getToken('token_id'); } diff --git a/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.php b/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.php index deccfaa53bc0..5046cc0deca1 100644 --- a/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.php +++ b/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; +use Symfony\Component\Security\Csrf\Exception\TokenNotFoundException; use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage; /** @@ -88,13 +89,13 @@ public function testGetExistingTokenFromActiveSession() public function testGetNonExistingTokenFromClosedSession() { - $this->expectException(\Symfony\Component\Security\Csrf\Exception\TokenNotFoundException::class); + $this->expectException(TokenNotFoundException::class); $this->storage->getToken('token_id'); } public function testGetNonExistingTokenFromActiveSession() { - $this->expectException(\Symfony\Component\Security\Csrf\Exception\TokenNotFoundException::class); + $this->expectException(TokenNotFoundException::class); $this->session->start(); $this->storage->getToken('token_id'); } diff --git a/src/Symfony/Component/Security/Guard/Tests/Authenticator/FormLoginAuthenticatorTest.php b/src/Symfony/Component/Security/Guard/Tests/Authenticator/FormLoginAuthenticatorTest.php index bab0d70b82f0..81c2143632b5 100644 --- a/src/Symfony/Component/Security/Guard/Tests/Authenticator/FormLoginAuthenticatorTest.php +++ b/src/Symfony/Component/Security/Guard/Tests/Authenticator/FormLoginAuthenticatorTest.php @@ -12,8 +12,10 @@ namespace Symfony\Component\Security\Guard\Tests\Authenticator; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Core\User\UserInterface; @@ -36,7 +38,7 @@ public function testAuthenticationFailureWithoutSession() { $failureResponse = $this->authenticator->onAuthenticationFailure($this->requestWithoutSession, new AuthenticationException()); - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\RedirectResponse::class, $failureResponse); + $this->assertInstanceOf(RedirectResponse::class, $failureResponse); $this->assertEquals(self::LOGIN_URL, $failureResponse->getTargetUrl()); } @@ -48,7 +50,7 @@ public function testAuthenticationFailureWithSession() $failureResponse = $this->authenticator->onAuthenticationFailure($this->requestWithSession, new AuthenticationException()); - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\RedirectResponse::class, $failureResponse); + $this->assertInstanceOf(RedirectResponse::class, $failureResponse); $this->assertEquals(self::LOGIN_URL, $failureResponse->getTargetUrl()); } @@ -63,7 +65,7 @@ public function testStartWithoutSession() { $failureResponse = $this->authenticator->start($this->requestWithoutSession, new AuthenticationException()); - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\RedirectResponse::class, $failureResponse); + $this->assertInstanceOf(RedirectResponse::class, $failureResponse); $this->assertEquals(self::LOGIN_URL, $failureResponse->getTargetUrl()); } @@ -71,7 +73,7 @@ public function testStartWithSession() { $failureResponse = $this->authenticator->start($this->requestWithSession, new AuthenticationException()); - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\RedirectResponse::class, $failureResponse); + $this->assertInstanceOf(RedirectResponse::class, $failureResponse); $this->assertEquals(self::LOGIN_URL, $failureResponse->getTargetUrl()); } @@ -80,9 +82,7 @@ protected function setUp(): void $this->requestWithoutSession = new Request([], [], [], [], [], []); $this->requestWithSession = new Request([], [], [], [], [], []); - $session = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\SessionInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $session = $this->createMock(SessionInterface::class); $this->requestWithSession->setSession($session); $this->authenticator = new TestFormLoginAuthenticator(); diff --git a/src/Symfony/Component/Security/Guard/Tests/Firewall/GuardAuthenticationListenerTest.php b/src/Symfony/Component/Security/Guard/Tests/Firewall/GuardAuthenticationListenerTest.php index 7167ba3dc46b..7d1c8e724635 100644 --- a/src/Symfony/Component/Security/Guard/Tests/Firewall/GuardAuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Guard/Tests/Firewall/GuardAuthenticationListenerTest.php @@ -12,13 +12,18 @@ namespace Symfony\Component\Security\Guard\Tests\Firewall; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Guard\AuthenticatorInterface; use Symfony\Component\Security\Guard\Firewall\GuardAuthenticationListener; +use Symfony\Component\Security\Guard\GuardAuthenticatorHandler; use Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken; +use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface; /** * @author Ryan Weaver @@ -35,8 +40,8 @@ class GuardAuthenticationListenerTest extends TestCase public function testHandleSuccess() { - $authenticator = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); - $authenticateToken = $this->getMockBuilder(TokenInterface::class)->getMock(); + $authenticator = $this->createMock(AuthenticatorInterface::class); + $authenticateToken = $this->createMock(TokenInterface::class); $providerKey = 'my_firewall'; $credentials = ['username' => 'weaverryan', 'password' => 'all_your_base']; @@ -90,8 +95,8 @@ public function testHandleSuccess() public function testHandleSuccessStopsAfterResponseIsSet() { - $authenticator1 = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); - $authenticator2 = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); + $authenticator1 = $this->createMock(AuthenticatorInterface::class); + $authenticator2 = $this->createMock(AuthenticatorInterface::class); // mock the first authenticator to fail, and set a Response $authenticator1 @@ -124,8 +129,8 @@ public function testHandleSuccessStopsAfterResponseIsSet() public function testHandleSuccessWithRememberMe() { - $authenticator = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); - $authenticateToken = $this->getMockBuilder(TokenInterface::class)->getMock(); + $authenticator = $this->createMock(AuthenticatorInterface::class); + $authenticateToken = $this->createMock(TokenInterface::class); $providerKey = 'my_firewall_with_rememberme'; $authenticator @@ -172,7 +177,7 @@ public function testHandleSuccessWithRememberMe() public function testHandleCatchesAuthenticationException() { - $authenticator = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); + $authenticator = $this->createMock(AuthenticatorInterface::class); $providerKey = 'my_firewall2'; $authException = new AuthenticationException('Get outta here crazy user with a bad password!'); @@ -208,7 +213,7 @@ public function testHandleCatchesAuthenticationException() public function testSupportsReturnFalseSkipAuth() { - $authenticator = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); + $authenticator = $this->createMock(AuthenticatorInterface::class); $providerKey = 'my_firewall4'; $authenticator @@ -235,7 +240,7 @@ public function testSupportsReturnFalseSkipAuth() public function testReturnNullFromGetCredentials() { $this->expectException(\UnexpectedValueException::class); - $authenticator = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); + $authenticator = $this->createMock(AuthenticatorInterface::class); $providerKey = 'my_firewall4'; $authenticator @@ -262,17 +267,11 @@ public function testReturnNullFromGetCredentials() protected function setUp(): void { - $this->authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->guardAuthenticatorHandler = $this->getMockBuilder(\Symfony\Component\Security\Guard\GuardAuthenticatorHandler::class) - ->disableOriginalConstructor() - ->getMock(); - + $this->authenticationManager = $this->createMock(AuthenticationProviderManager::class); + $this->guardAuthenticatorHandler = $this->createMock(GuardAuthenticatorHandler::class); $this->request = new Request([], [], [], [], [], []); - $this->event = $this->getMockBuilder(\Symfony\Component\HttpKernel\Event\RequestEvent::class) + $this->event = $this->getMockBuilder(RequestEvent::class) ->disableOriginalConstructor() ->setMethods(['getRequest']) ->getMock(); @@ -281,8 +280,8 @@ protected function setUp(): void ->method('getRequest') ->willReturn($this->request); - $this->logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); - $this->rememberMeServices = $this->getMockBuilder(\Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface::class)->getMock(); + $this->logger = $this->createMock(LoggerInterface::class); + $this->rememberMeServices = $this->createMock(RememberMeServicesInterface::class); } protected function tearDown(): void diff --git a/src/Symfony/Component/Security/Guard/Tests/GuardAuthenticatorHandlerTest.php b/src/Symfony/Component/Security/Guard/Tests/GuardAuthenticatorHandlerTest.php index e115891bbab4..f35daf6de2f2 100644 --- a/src/Symfony/Component/Security/Guard/Tests/GuardAuthenticatorHandlerTest.php +++ b/src/Symfony/Component/Security/Guard/Tests/GuardAuthenticatorHandlerTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; @@ -174,12 +175,12 @@ public function testSessionIsNotInstantiatedOnStatelessFirewall() protected function setUp(): void { - $this->tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); - $this->dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); - $this->token = $this->getMockBuilder(TokenInterface::class)->getMock(); + $this->tokenStorage = $this->createMock(TokenStorageInterface::class); + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); + $this->token = $this->createMock(TokenInterface::class); $this->request = new Request([], [], [], [], [], []); - $this->sessionStrategy = $this->getMockBuilder(SessionAuthenticationStrategyInterface::class)->getMock(); - $this->guardAuthenticator = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); + $this->sessionStrategy = $this->createMock(SessionAuthenticationStrategyInterface::class); + $this->guardAuthenticator = $this->createMock(AuthenticatorInterface::class); } protected function tearDown(): void @@ -193,7 +194,7 @@ protected function tearDown(): void private function configurePreviousSession() { - $session = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\SessionInterface::class)->getMock(); + $session = $this->createMock(SessionInterface::class); $session->expects($this->any()) ->method('getName') ->willReturn('test_session_name'); diff --git a/src/Symfony/Component/Security/Guard/Tests/Provider/GuardAuthenticationProviderTest.php b/src/Symfony/Component/Security/Guard/Tests/Provider/GuardAuthenticationProviderTest.php index 5ecf12e4c6c5..ef21ebbb4748 100644 --- a/src/Symfony/Component/Security/Guard/Tests/Provider/GuardAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Guard/Tests/Provider/GuardAuthenticationProviderTest.php @@ -12,8 +12,12 @@ namespace Symfony\Component\Security\Guard\Tests\Provider; use PHPUnit\Framework\TestCase; +use Symfony\Component\Security\Core\Exception\AuthenticationException; +use Symfony\Component\Security\Core\Exception\AuthenticationExpiredException; use Symfony\Component\Security\Core\Exception\BadCredentialsException; +use Symfony\Component\Security\Core\User\UserCheckerInterface; use Symfony\Component\Security\Core\User\UserInterface; +use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Guard\AuthenticatorInterface; use Symfony\Component\Security\Guard\Provider\GuardAuthenticationProvider; use Symfony\Component\Security\Guard\Token\GuardTokenInterface; @@ -33,9 +37,9 @@ public function testAuthenticate() { $providerKey = 'my_cool_firewall'; - $authenticatorA = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); - $authenticatorB = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); - $authenticatorC = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); + $authenticatorA = $this->createMock(AuthenticatorInterface::class); + $authenticatorB = $this->createMock(AuthenticatorInterface::class); + $authenticatorC = $this->createMock(AuthenticatorInterface::class); $authenticators = [$authenticatorA, $authenticatorB, $authenticatorC]; // called 2 times - for authenticator A and B (stops on B because of match) @@ -58,7 +62,7 @@ public function testAuthenticate() $authenticatorC->expects($this->never()) ->method('getUser'); - $mockedUser = $this->getMockBuilder(UserInterface::class)->getMock(); + $mockedUser = $this->createMock(UserInterface::class); $authenticatorB->expects($this->once()) ->method('getUser') ->with($enteredCredentials, $this->userProvider) @@ -69,7 +73,7 @@ public function testAuthenticate() ->with($enteredCredentials, $mockedUser) // authentication works! ->willReturn(true); - $authedToken = $this->getMockBuilder(GuardTokenInterface::class)->getMock(); + $authedToken = $this->createMock(GuardTokenInterface::class); $authenticatorB->expects($this->once()) ->method('createAuthenticatedToken') ->with($mockedUser, $providerKey) @@ -128,7 +132,7 @@ public function testCheckCredentialsReturningNonTrueFailsAuthentication() $this->expectException(BadCredentialsException::class); $providerKey = 'my_uncool_firewall'; - $authenticator = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); + $authenticator = $this->createMock(AuthenticatorInterface::class); // make sure the authenticator is used $this->preAuthenticationToken->expects($this->any()) @@ -140,7 +144,7 @@ public function testCheckCredentialsReturningNonTrueFailsAuthentication() ->method('getCredentials') ->willReturn('non-null-value'); - $mockedUser = $this->getMockBuilder(UserInterface::class)->getMock(); + $mockedUser = $this->createMock(UserInterface::class); $authenticator->expects($this->once()) ->method('getUser') ->willReturn($mockedUser); @@ -156,12 +160,12 @@ public function testCheckCredentialsReturningNonTrueFailsAuthentication() public function testGuardWithNoLongerAuthenticatedTriggersLogout() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AuthenticationExpiredException::class); + $this->expectException(AuthenticationExpiredException::class); $providerKey = 'my_firewall_abc'; // create a token and mark it as NOT authenticated anymore // this mimics what would happen if a user "changed" between request - $mockedUser = $this->getMockBuilder(UserInterface::class)->getMock(); + $mockedUser = $this->createMock(UserInterface::class); $token = new PostAuthenticationGuardToken($mockedUser, $providerKey, ['ROLE_USER']); $token->setAuthenticated(false); @@ -171,11 +175,11 @@ public function testGuardWithNoLongerAuthenticatedTriggersLogout() public function testSupportsChecksGuardAuthenticatorsTokenOrigin() { - $authenticatorA = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); - $authenticatorB = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); + $authenticatorA = $this->createMock(AuthenticatorInterface::class); + $authenticatorB = $this->createMock(AuthenticatorInterface::class); $authenticators = [$authenticatorA, $authenticatorB]; - $mockedUser = $this->getMockBuilder(UserInterface::class)->getMock(); + $mockedUser = $this->createMock(UserInterface::class); $provider = new GuardAuthenticationProvider($authenticators, $this->userProvider, 'first_firewall', $this->userChecker); $token = new PreAuthenticationGuardToken($mockedUser, 'first_firewall_1'); @@ -189,12 +193,12 @@ public function testSupportsChecksGuardAuthenticatorsTokenOrigin() public function testAuthenticateFailsOnNonOriginatingToken() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AuthenticationException::class); + $this->expectException(AuthenticationException::class); $this->expectExceptionMessageMatches('/second_firewall_0/'); - $authenticatorA = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); + $authenticatorA = $this->createMock(AuthenticatorInterface::class); $authenticators = [$authenticatorA]; - $mockedUser = $this->getMockBuilder(UserInterface::class)->getMock(); + $mockedUser = $this->createMock(UserInterface::class); $provider = new GuardAuthenticationProvider($authenticators, $this->userProvider, 'first_firewall', $this->userChecker); $token = new PreAuthenticationGuardToken($mockedUser, 'second_firewall_0'); @@ -203,11 +207,9 @@ public function testAuthenticateFailsOnNonOriginatingToken() protected function setUp(): void { - $this->userProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserProviderInterface::class)->getMock(); - $this->userChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(); - $this->preAuthenticationToken = $this->getMockBuilder(PreAuthenticationGuardToken::class) - ->disableOriginalConstructor() - ->getMock(); + $this->userProvider = $this->createMock(UserProviderInterface::class); + $this->userChecker = $this->createMock(UserCheckerInterface::class); + $this->preAuthenticationToken = $this->createMock(PreAuthenticationGuardToken::class); } protected function tearDown(): void diff --git a/src/Symfony/Component/Security/Http/Tests/AccessMapTest.php b/src/Symfony/Component/Security/Http/Tests/AccessMapTest.php index 865554b25a45..884859ac3c12 100644 --- a/src/Symfony/Component/Security/Http/Tests/AccessMapTest.php +++ b/src/Symfony/Component/Security/Http/Tests/AccessMapTest.php @@ -12,13 +12,15 @@ namespace Symfony\Component\Security\Http\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestMatcherInterface; use Symfony\Component\Security\Http\AccessMap; class AccessMapTest extends TestCase { public function testReturnsFirstMatchedPattern() { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->getMock(); + $request = $this->createMock(Request::class); $requestMatcher1 = $this->getRequestMatcher($request, false); $requestMatcher2 = $this->getRequestMatcher($request, true); @@ -31,7 +33,7 @@ public function testReturnsFirstMatchedPattern() public function testReturnsEmptyPatternIfNoneMatched() { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->getMock(); + $request = $this->createMock(Request::class); $requestMatcher = $this->getRequestMatcher($request, false); $map = new AccessMap(); @@ -42,7 +44,7 @@ public function testReturnsEmptyPatternIfNoneMatched() private function getRequestMatcher($request, $matches) { - $requestMatcher = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestMatcherInterface::class)->getMock(); + $requestMatcher = $this->createMock(RequestMatcherInterface::class); $requestMatcher->expects($this->once()) ->method('matches')->with($request) ->willReturn($matches); diff --git a/src/Symfony/Component/Security/Http/Tests/Authentication/DefaultAuthenticationFailureHandlerTest.php b/src/Symfony/Component/Security/Http/Tests/Authentication/DefaultAuthenticationFailureHandlerTest.php index b24769aa75be..d95027560b70 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authentication/DefaultAuthenticationFailureHandlerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authentication/DefaultAuthenticationFailureHandlerTest.php @@ -12,11 +12,17 @@ namespace Symfony\Component\Security\Http\Tests\Authentication; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; +use Symfony\Component\HttpFoundation\ParameterBag; use Symfony\Component\HttpFoundation\RedirectResponse; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler; +use Symfony\Component\Security\Http\HttpUtils; class DefaultAuthenticationFailureHandlerTest extends TestCase { @@ -29,14 +35,14 @@ class DefaultAuthenticationFailureHandlerTest extends TestCase protected function setUp(): void { - $this->httpKernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); - $this->httpUtils = $this->getMockBuilder(\Symfony\Component\Security\Http\HttpUtils::class)->getMock(); - $this->logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $this->httpKernel = $this->createMock(HttpKernelInterface::class); + $this->httpUtils = $this->createMock(HttpUtils::class); + $this->logger = $this->createMock(LoggerInterface::class); - $this->session = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\SessionInterface::class)->getMock(); - $this->request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->getMock(); + $this->session = $this->createMock(SessionInterface::class); + $this->request = $this->createMock(Request::class); $this->request->expects($this->any())->method('getSession')->willReturn($this->session); - $this->exception = $this->getMockBuilder(\Symfony\Component\Security\Core\Exception\AuthenticationException::class)->setMethods(['getMessage'])->getMock(); + $this->exception = $this->getMockBuilder(AuthenticationException::class)->setMethods(['getMessage'])->getMock(); } public function testForward() @@ -183,8 +189,8 @@ public function testFailurePathParameterCanBeOverwritten() private function getRequest() { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->getMock(); - $request->attributes = $this->getMockBuilder(\Symfony\Component\HttpFoundation\ParameterBag::class)->getMock(); + $request = $this->createMock(Request::class); + $request->attributes = $this->createMock(ParameterBag::class); return $request; } diff --git a/src/Symfony/Component/Security/Http/Tests/Authentication/DefaultAuthenticationSuccessHandlerTest.php b/src/Symfony/Component/Security/Http/Tests/Authentication/DefaultAuthenticationSuccessHandlerTest.php index b327257909bd..9ed1822bf2c7 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authentication/DefaultAuthenticationSuccessHandlerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authentication/DefaultAuthenticationSuccessHandlerTest.php @@ -13,6 +13,9 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Session\SessionInterface; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler; use Symfony\Component\Security\Http\HttpUtils; @@ -23,10 +26,10 @@ class DefaultAuthenticationSuccessHandlerTest extends TestCase */ public function testRequestRedirections(Request $request, $options, $redirectedUrl) { - $urlGenerator = $this->getMockBuilder(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class)->getMock(); + $urlGenerator = $this->createMock(UrlGeneratorInterface::class); $urlGenerator->expects($this->any())->method('generate')->willReturn('http://localhost/login'); $httpUtils = new HttpUtils($urlGenerator); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $handler = new DefaultAuthenticationSuccessHandler($httpUtils, $options); if ($request->hasSession()) { $handler->setProviderKey('admin'); @@ -36,7 +39,7 @@ public function testRequestRedirections(Request $request, $options, $redirectedU public function getRequestRedirections() { - $session = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\SessionInterface::class)->getMock(); + $session = $this->createMock(SessionInterface::class); $session->expects($this->once())->method('get')->with('_security.admin.target_path')->willReturn('/admin/dashboard'); $session->expects($this->once())->method('remove')->with('_security.admin.target_path'); $requestWithSession = Request::create('/'); diff --git a/src/Symfony/Component/Security/Http/Tests/Authentication/SimpleAuthenticationHandlerTest.php b/src/Symfony/Component/Security/Http/Tests/Authentication/SimpleAuthenticationHandlerTest.php index 3e7d45b0007d..5907654d15f2 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authentication/SimpleAuthenticationHandlerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authentication/SimpleAuthenticationHandlerTest.php @@ -12,8 +12,10 @@ namespace Symfony\Component\Security\Http\Tests\Authentication; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface; use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface; @@ -38,11 +40,11 @@ class SimpleAuthenticationHandlerTest extends TestCase protected function setUp(): void { - $this->successHandler = $this->getMockBuilder(AuthenticationSuccessHandlerInterface::class)->getMock(); - $this->failureHandler = $this->getMockBuilder(AuthenticationFailureHandlerInterface::class)->getMock(); + $this->successHandler = $this->createMock(AuthenticationSuccessHandlerInterface::class); + $this->failureHandler = $this->createMock(AuthenticationFailureHandlerInterface::class); - $this->request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->getMock(); - $this->token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $this->request = $this->createMock(Request::class); + $this->token = $this->createMock(TokenInterface::class); // No methods are invoked on the exception; we just assert on its class $this->authenticationException = new AuthenticationException(); @@ -51,7 +53,7 @@ protected function setUp(): void public function testOnAuthenticationSuccessFallsBackToDefaultHandlerIfSimpleIsNotASuccessHandler() { - $authenticator = $this->getMockBuilder(SimpleAuthenticatorInterface::class)->getMock(); + $authenticator = $this->createMock(SimpleAuthenticatorInterface::class); $this->successHandler->expects($this->once()) ->method('onAuthenticationSuccess') @@ -69,7 +71,7 @@ public function testOnAuthenticationSuccessCallsSimpleAuthenticator() $this->successHandler->expects($this->never()) ->method('onAuthenticationSuccess'); - $authenticator = $this->getMockForAbstractClass(\Symfony\Component\Security\Http\Tests\Authentication\TestSuccessHandlerInterface::class); + $authenticator = $this->getMockForAbstractClass(TestSuccessHandlerInterface::class); $authenticator->expects($this->once()) ->method('onAuthenticationSuccess') ->with($this->request, $this->token) @@ -88,7 +90,7 @@ public function testOnAuthenticationSuccessThrowsAnExceptionIfNonResponseIsRetur $this->successHandler->expects($this->never()) ->method('onAuthenticationSuccess'); - $authenticator = $this->getMockForAbstractClass(\Symfony\Component\Security\Http\Tests\Authentication\TestSuccessHandlerInterface::class); + $authenticator = $this->getMockForAbstractClass(TestSuccessHandlerInterface::class); $authenticator->expects($this->once()) ->method('onAuthenticationSuccess') ->with($this->request, $this->token) @@ -105,7 +107,7 @@ public function testOnAuthenticationSuccessFallsBackToDefaultHandlerIfNullIsRetu ->with($this->request, $this->token) ->willReturn($this->response); - $authenticator = $this->getMockForAbstractClass(\Symfony\Component\Security\Http\Tests\Authentication\TestSuccessHandlerInterface::class); + $authenticator = $this->getMockForAbstractClass(TestSuccessHandlerInterface::class); $authenticator->expects($this->once()) ->method('onAuthenticationSuccess') ->with($this->request, $this->token) @@ -119,7 +121,7 @@ public function testOnAuthenticationSuccessFallsBackToDefaultHandlerIfNullIsRetu public function testOnAuthenticationFailureFallsBackToDefaultHandlerIfSimpleIsNotAFailureHandler() { - $authenticator = $this->getMockBuilder(SimpleAuthenticatorInterface::class)->getMock(); + $authenticator = $this->createMock(SimpleAuthenticatorInterface::class); $this->failureHandler->expects($this->once()) ->method('onAuthenticationFailure') @@ -137,7 +139,7 @@ public function testOnAuthenticationFailureCallsSimpleAuthenticator() $this->failureHandler->expects($this->never()) ->method('onAuthenticationFailure'); - $authenticator = $this->getMockForAbstractClass(\Symfony\Component\Security\Http\Tests\Authentication\TestFailureHandlerInterface::class); + $authenticator = $this->getMockForAbstractClass(TestFailureHandlerInterface::class); $authenticator->expects($this->once()) ->method('onAuthenticationFailure') ->with($this->request, $this->authenticationException) @@ -156,7 +158,7 @@ public function testOnAuthenticationFailureThrowsAnExceptionIfNonResponseIsRetur $this->failureHandler->expects($this->never()) ->method('onAuthenticationFailure'); - $authenticator = $this->getMockForAbstractClass(\Symfony\Component\Security\Http\Tests\Authentication\TestFailureHandlerInterface::class); + $authenticator = $this->getMockForAbstractClass(TestFailureHandlerInterface::class); $authenticator->expects($this->once()) ->method('onAuthenticationFailure') ->with($this->request, $this->authenticationException) @@ -173,7 +175,7 @@ public function testOnAuthenticationFailureFallsBackToDefaultHandlerIfNullIsRetu ->with($this->request, $this->authenticationException) ->willReturn($this->response); - $authenticator = $this->getMockForAbstractClass(\Symfony\Component\Security\Http\Tests\Authentication\TestFailureHandlerInterface::class); + $authenticator = $this->getMockForAbstractClass(TestFailureHandlerInterface::class); $authenticator->expects($this->once()) ->method('onAuthenticationFailure') ->with($this->request, $this->authenticationException) diff --git a/src/Symfony/Component/Security/Http/Tests/Controller/UserValueResolverTest.php b/src/Symfony/Component/Security/Http/Tests/Controller/UserValueResolverTest.php index a3fb526a2490..bfc182c89c8b 100644 --- a/src/Symfony/Component/Security/Http/Tests/Controller/UserValueResolverTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Controller/UserValueResolverTest.php @@ -34,7 +34,7 @@ public function testResolveNoToken() public function testResolveNoUser() { - $mock = $this->getMockBuilder(UserInterface::class)->getMock(); + $mock = $this->createMock(UserInterface::class); $token = new UsernamePasswordToken('username', 'password', 'provider'); $tokenStorage = new TokenStorage(); $tokenStorage->setToken($token); @@ -56,7 +56,7 @@ public function testResolveWrongType() public function testResolve() { - $user = $this->getMockBuilder(UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $token = new UsernamePasswordToken($user, 'password', 'provider'); $tokenStorage = new TokenStorage(); $tokenStorage->setToken($token); @@ -70,7 +70,7 @@ public function testResolve() public function testIntegration() { - $user = $this->getMockBuilder(UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $token = new UsernamePasswordToken($user, 'password', 'provider'); $tokenStorage = new TokenStorage(); $tokenStorage->setToken($token); diff --git a/src/Symfony/Component/Security/Http/Tests/EntryPoint/BasicAuthenticationEntryPointTest.php b/src/Symfony/Component/Security/Http/Tests/EntryPoint/BasicAuthenticationEntryPointTest.php index 7c7f3a1f8ba4..0d17b5c8bbd8 100644 --- a/src/Symfony/Component/Security/Http/Tests/EntryPoint/BasicAuthenticationEntryPointTest.php +++ b/src/Symfony/Component/Security/Http/Tests/EntryPoint/BasicAuthenticationEntryPointTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Http\Tests\EntryPoint; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\EntryPoint\BasicAuthenticationEntryPoint; @@ -19,7 +20,7 @@ class BasicAuthenticationEntryPointTest extends TestCase { public function testStart() { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->getMock(); + $request = $this->createMock(Request::class); $authException = new AuthenticationException('The exception message'); @@ -32,7 +33,7 @@ public function testStart() public function testStartWithoutAuthException() { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->getMock(); + $request = $this->createMock(Request::class); $entryPoint = new BasicAuthenticationEntryPoint('TheRealmName'); diff --git a/src/Symfony/Component/Security/Http/Tests/EntryPoint/FormAuthenticationEntryPointTest.php b/src/Symfony/Component/Security/Http/Tests/EntryPoint/FormAuthenticationEntryPointTest.php index 432c8dd7a34c..462607a46a1e 100644 --- a/src/Symfony/Component/Security/Http/Tests/EntryPoint/FormAuthenticationEntryPointTest.php +++ b/src/Symfony/Component/Security/Http/Tests/EntryPoint/FormAuthenticationEntryPointTest.php @@ -13,19 +13,21 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\RedirectResponse; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\Security\Http\EntryPoint\FormAuthenticationEntryPoint; +use Symfony\Component\Security\Http\HttpUtils; class FormAuthenticationEntryPointTest extends TestCase { public function testStart() { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->disableOriginalConstructor()->disableOriginalClone()->getMock(); + $request = $this->createMock(Request::class); $response = new RedirectResponse('/the/login/path'); - $httpKernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); - $httpUtils = $this->getMockBuilder(\Symfony\Component\Security\Http\HttpUtils::class)->getMock(); + $httpKernel = $this->createMock(HttpKernelInterface::class); + $httpUtils = $this->createMock(HttpUtils::class); $httpUtils ->expects($this->once()) ->method('createRedirectResponse') @@ -40,11 +42,11 @@ public function testStart() public function testStartWithUseForward() { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->disableOriginalConstructor()->disableOriginalClone()->getMock(); - $subRequest = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->disableOriginalConstructor()->disableOriginalClone()->getMock(); + $request = $this->createMock(Request::class); + $subRequest = $this->createMock(Request::class); $response = new Response('', 200); - $httpUtils = $this->getMockBuilder(\Symfony\Component\Security\Http\HttpUtils::class)->getMock(); + $httpUtils = $this->createMock(HttpUtils::class); $httpUtils ->expects($this->once()) ->method('createRequest') @@ -52,7 +54,7 @@ public function testStartWithUseForward() ->willReturn($subRequest) ; - $httpKernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $httpKernel = $this->createMock(HttpKernelInterface::class); $httpKernel ->expects($this->once()) ->method('handle') diff --git a/src/Symfony/Component/Security/Http/Tests/EntryPoint/RetryAuthenticationEntryPointTest.php b/src/Symfony/Component/Security/Http/Tests/EntryPoint/RetryAuthenticationEntryPointTest.php index 643240918c1d..13dff28fcebc 100644 --- a/src/Symfony/Component/Security/Http/Tests/EntryPoint/RetryAuthenticationEntryPointTest.php +++ b/src/Symfony/Component/Security/Http/Tests/EntryPoint/RetryAuthenticationEntryPointTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Http\Tests\EntryPoint; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Http\EntryPoint\RetryAuthenticationEntryPoint; @@ -25,7 +26,7 @@ public function testStart($httpPort, $httpsPort, $request, $expectedUrl) $entryPoint = new RetryAuthenticationEntryPoint($httpPort, $httpsPort); $response = $entryPoint->start($request); - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\RedirectResponse::class, $response); + $this->assertInstanceOf(RedirectResponse::class, $response); $this->assertEquals($expectedUrl, $response->headers->get('Location')); } diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/AbstractPreAuthenticatedListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/AbstractPreAuthenticatedListenerTest.php index 22b528edc7a9..83909a73ad8a 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/AbstractPreAuthenticatedListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/AbstractPreAuthenticatedListenerTest.php @@ -14,9 +14,13 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; use Symfony\Component\Security\Core\Exception\AuthenticationException; +use Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener; class AbstractPreAuthenticatedListenerTest extends TestCase { @@ -26,9 +30,9 @@ public function testHandleWithValidValues() $request = new Request([], [], [], [], [], []); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') @@ -40,7 +44,7 @@ public function testHandleWithValidValues() ->with($this->equalTo($token)) ; - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $authenticationManager ->expects($this->once()) ->method('authenticate') @@ -48,7 +52,7 @@ public function testHandleWithValidValues() ->willReturn($token) ; - $listener = $this->getMockForAbstractClass(\Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener::class, [ + $listener = $this->getMockForAbstractClass(AbstractPreAuthenticatedListener::class, [ $tokenStorage, $authenticationManager, 'TheProviderKey', @@ -58,7 +62,7 @@ public function testHandleWithValidValues() ->method('getPreAuthenticatedData') ->willReturn($userCredentials); - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') @@ -74,7 +78,7 @@ public function testHandleWhenAuthenticationFails() $request = new Request([], [], [], [], [], []); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') @@ -86,7 +90,7 @@ public function testHandleWhenAuthenticationFails() ; $exception = new AuthenticationException('Authentication failed.'); - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $authenticationManager ->expects($this->once()) ->method('authenticate') @@ -94,7 +98,8 @@ public function testHandleWhenAuthenticationFails() ->willThrowException($exception) ; - $listener = $this->getMockForAbstractClass(\Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener::class, [ + $listener = $this->getMockForAbstractClass( + AbstractPreAuthenticatedListener::class, [ $tokenStorage, $authenticationManager, 'TheProviderKey', @@ -104,7 +109,7 @@ public function testHandleWhenAuthenticationFails() ->method('getPreAuthenticatedData') ->willReturn($userCredentials); - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') @@ -122,7 +127,7 @@ public function testHandleWhenAuthenticationFailsWithDifferentToken() $request = new Request([], [], [], [], [], []); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') @@ -134,7 +139,7 @@ public function testHandleWhenAuthenticationFailsWithDifferentToken() ; $exception = new AuthenticationException('Authentication failed.'); - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $authenticationManager ->expects($this->once()) ->method('authenticate') @@ -142,7 +147,8 @@ public function testHandleWhenAuthenticationFailsWithDifferentToken() ->willThrowException($exception) ; - $listener = $this->getMockForAbstractClass(\Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener::class, [ + $listener = $this->getMockForAbstractClass( + AbstractPreAuthenticatedListener::class, [ $tokenStorage, $authenticationManager, 'TheProviderKey', @@ -152,7 +158,7 @@ public function testHandleWhenAuthenticationFailsWithDifferentToken() ->method('getPreAuthenticatedData') ->willReturn($userCredentials); - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') @@ -170,20 +176,21 @@ public function testHandleWithASimilarAuthenticatedToken() $token = new PreAuthenticatedToken('TheUser', 'TheCredentials', 'TheProviderKey', ['ROLE_FOO']); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') ->willReturn($token) ; - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $authenticationManager ->expects($this->never()) ->method('authenticate') ; - $listener = $this->getMockForAbstractClass(\Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener::class, [ + $listener = $this->getMockForAbstractClass( + AbstractPreAuthenticatedListener::class, [ $tokenStorage, $authenticationManager, 'TheProviderKey', @@ -193,7 +200,7 @@ public function testHandleWithASimilarAuthenticatedToken() ->method('getPreAuthenticatedData') ->willReturn($userCredentials); - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') @@ -211,7 +218,7 @@ public function testHandleWithAnInvalidSimilarToken() $token = new PreAuthenticatedToken('AnotherUser', 'TheCredentials', 'TheProviderKey', ['ROLE_FOO']); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') @@ -224,7 +231,7 @@ public function testHandleWithAnInvalidSimilarToken() ; $exception = new AuthenticationException('Authentication failed.'); - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $authenticationManager ->expects($this->once()) ->method('authenticate') @@ -232,7 +239,8 @@ public function testHandleWithAnInvalidSimilarToken() ->willThrowException($exception) ; - $listener = $this->getMockForAbstractClass(\Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener::class, [ + $listener = $this->getMockForAbstractClass( + AbstractPreAuthenticatedListener::class, [ $tokenStorage, $authenticationManager, 'TheProviderKey', @@ -242,7 +250,7 @@ public function testHandleWithAnInvalidSimilarToken() ->method('getPreAuthenticatedData') ->willReturn($userCredentials); - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.php index ccc0e6cdf450..c57cf9629055 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.php @@ -33,7 +33,7 @@ public function testHandleWhenTheAccessDecisionManagerDecidesToRefuseAccess() $this->expectException(AccessDeniedException::class); $request = new Request(); - $accessMap = $this->getMockBuilder(AccessMapInterface::class)->getMock(); + $accessMap = $this->createMock(AccessMapInterface::class); $accessMap ->expects($this->any()) ->method('getPatterns') @@ -41,21 +41,21 @@ public function testHandleWhenTheAccessDecisionManagerDecidesToRefuseAccess() ->willReturn([['foo' => 'bar'], null]) ; - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $token ->expects($this->any()) ->method('isAuthenticated') ->willReturn(true) ; - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') ->willReturn($token) ; - $accessDecisionManager = $this->getMockBuilder(AccessDecisionManagerInterface::class)->getMock(); + $accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class); $accessDecisionManager ->expects($this->once()) ->method('decide') @@ -67,7 +67,7 @@ public function testHandleWhenTheAccessDecisionManagerDecidesToRefuseAccess() $tokenStorage, $accessDecisionManager, $accessMap, - $this->getMockBuilder(AuthenticationManagerInterface::class)->getMock() + $this->createMock(AuthenticationManagerInterface::class) ); $listener(new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST)); @@ -77,7 +77,7 @@ public function testHandleWhenTheTokenIsNotAuthenticated() { $request = new Request(); - $accessMap = $this->getMockBuilder(AccessMapInterface::class)->getMock(); + $accessMap = $this->createMock(AccessMapInterface::class); $accessMap ->expects($this->any()) ->method('getPatterns') @@ -85,21 +85,21 @@ public function testHandleWhenTheTokenIsNotAuthenticated() ->willReturn([['foo' => 'bar'], null]) ; - $notAuthenticatedToken = $this->getMockBuilder(TokenInterface::class)->getMock(); + $notAuthenticatedToken = $this->createMock(TokenInterface::class); $notAuthenticatedToken ->expects($this->any()) ->method('isAuthenticated') ->willReturn(false) ; - $authenticatedToken = $this->getMockBuilder(TokenInterface::class)->getMock(); + $authenticatedToken = $this->createMock(TokenInterface::class); $authenticatedToken ->expects($this->any()) ->method('isAuthenticated') ->willReturn(true) ; - $authManager = $this->getMockBuilder(AuthenticationManagerInterface::class)->getMock(); + $authManager = $this->createMock(AuthenticationManagerInterface::class); $authManager ->expects($this->once()) ->method('authenticate') @@ -107,7 +107,7 @@ public function testHandleWhenTheTokenIsNotAuthenticated() ->willReturn($authenticatedToken) ; - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') @@ -119,7 +119,7 @@ public function testHandleWhenTheTokenIsNotAuthenticated() ->with($this->equalTo($authenticatedToken)) ; - $accessDecisionManager = $this->getMockBuilder(AccessDecisionManagerInterface::class)->getMock(); + $accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class); $accessDecisionManager ->expects($this->once()) ->method('decide') @@ -141,7 +141,7 @@ public function testHandleWhenThereIsNoAccessMapEntryMatchingTheRequest() { $request = new Request(); - $accessMap = $this->getMockBuilder(AccessMapInterface::class)->getMock(); + $accessMap = $this->createMock(AccessMapInterface::class); $accessMap ->expects($this->any()) ->method('getPatterns') @@ -149,13 +149,13 @@ public function testHandleWhenThereIsNoAccessMapEntryMatchingTheRequest() ->willReturn([null, null]) ; - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $token ->expects($this->never()) ->method('isAuthenticated') ; - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') @@ -164,9 +164,9 @@ public function testHandleWhenThereIsNoAccessMapEntryMatchingTheRequest() $listener = new AccessListener( $tokenStorage, - $this->getMockBuilder(AccessDecisionManagerInterface::class)->getMock(), + $this->createMock(AccessDecisionManagerInterface::class), $accessMap, - $this->getMockBuilder(AuthenticationManagerInterface::class)->getMock() + $this->createMock(AuthenticationManagerInterface::class) ); $listener(new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST)); @@ -176,7 +176,7 @@ public function testHandleWhenAccessMapReturnsEmptyAttributes() { $request = new Request(); - $accessMap = $this->getMockBuilder(AccessMapInterface::class)->getMock(); + $accessMap = $this->createMock(AccessMapInterface::class); $accessMap ->expects($this->any()) ->method('getPatterns') @@ -184,7 +184,7 @@ public function testHandleWhenAccessMapReturnsEmptyAttributes() ->willReturn([[], null]) ; - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->never()) ->method('getToken') @@ -192,9 +192,9 @@ public function testHandleWhenAccessMapReturnsEmptyAttributes() $listener = new AccessListener( $tokenStorage, - $this->getMockBuilder(AccessDecisionManagerInterface::class)->getMock(), + $this->createMock(AccessDecisionManagerInterface::class), $accessMap, - $this->getMockBuilder(AuthenticationManagerInterface::class)->getMock() + $this->createMock(AuthenticationManagerInterface::class) ); $event = new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST); @@ -205,7 +205,7 @@ public function testHandleWhenAccessMapReturnsEmptyAttributes() public function testHandleWhenTheSecurityTokenStorageHasNoToken() { $this->expectException(AuthenticationCredentialsNotFoundException::class); - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') @@ -214,7 +214,7 @@ public function testHandleWhenTheSecurityTokenStorageHasNoToken() $request = new Request(); - $accessMap = $this->getMockBuilder(AccessMapInterface::class)->getMock(); + $accessMap = $this->createMock(AccessMapInterface::class); $accessMap ->expects($this->any()) ->method('getPatterns') @@ -224,9 +224,9 @@ public function testHandleWhenTheSecurityTokenStorageHasNoToken() $listener = new AccessListener( $tokenStorage, - $this->getMockBuilder(AccessDecisionManagerInterface::class)->getMock(), + $this->createMock(AccessDecisionManagerInterface::class), $accessMap, - $this->getMockBuilder(AuthenticationManagerInterface::class)->getMock() + $this->createMock(AuthenticationManagerInterface::class) ); $listener(new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST)); @@ -236,7 +236,7 @@ public function testHandleMWithultipleAttributesShouldBeHandledAsAnd() { $request = new Request(); - $accessMap = $this->getMockBuilder(AccessMapInterface::class)->getMock(); + $accessMap = $this->createMock(AccessMapInterface::class); $accessMap ->expects($this->any()) ->method('getPatterns') @@ -244,7 +244,7 @@ public function testHandleMWithultipleAttributesShouldBeHandledAsAnd() ->willReturn([['foo' => 'bar', 'bar' => 'baz'], null]) ; - $authenticatedToken = $this->getMockBuilder(TokenInterface::class)->getMock(); + $authenticatedToken = $this->createMock(TokenInterface::class); $authenticatedToken ->expects($this->any()) ->method('isAuthenticated') @@ -254,7 +254,7 @@ public function testHandleMWithultipleAttributesShouldBeHandledAsAnd() $tokenStorage = new TokenStorage(); $tokenStorage->setToken($authenticatedToken); - $accessDecisionManager = $this->getMockBuilder(AccessDecisionManagerInterface::class)->getMock(); + $accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class); $accessDecisionManager ->expects($this->once()) ->method('decide') diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/AnonymousAuthenticationListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/AnonymousAuthenticationListenerTest.php index 5940ad2e6e75..522e0abc1c45 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/AnonymousAuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/AnonymousAuthenticationListenerTest.php @@ -12,28 +12,32 @@ namespace Symfony\Component\Security\Http\Tests\Firewall; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Http\Firewall\AnonymousAuthenticationListener; class AnonymousAuthenticationListenerTest extends TestCase { public function testHandleWithTokenStorageHavingAToken() { - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') - ->willReturn($this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()) + ->willReturn($this->createMock(TokenInterface::class)) ; $tokenStorage ->expects($this->never()) ->method('setToken') ; - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $authenticationManager ->expects($this->never()) ->method('authenticate') @@ -45,7 +49,7 @@ public function testHandleWithTokenStorageHavingAToken() public function testHandleWithTokenStorageHavingNoToken() { - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') @@ -54,7 +58,7 @@ public function testHandleWithTokenStorageHavingNoToken() $anonymousToken = new AnonymousToken('TheSecret', 'anon.', []); - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $authenticationManager ->expects($this->once()) ->method('authenticate') @@ -76,14 +80,14 @@ public function testHandleWithTokenStorageHavingNoToken() public function testHandledEventIsLogged() { - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); + $logger = $this->createMock(LoggerInterface::class); $logger->expects($this->once()) ->method('info') ->with('Populated the TokenStorage with an anonymous Token.') ; - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $listener = new AnonymousAuthenticationListener($tokenStorage, 'TheSecret', $logger, $authenticationManager); $listener(new RequestEvent($this->createMock(HttpKernelInterface::class), new Request(), HttpKernelInterface::MASTER_REQUEST)); diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/BasicAuthenticationListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/BasicAuthenticationListenerTest.php index 337a116b9ed9..f1e6c8bca7c0 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/BasicAuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/BasicAuthenticationListenerTest.php @@ -15,9 +15,15 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager; +use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface; use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; +use Symfony\Component\Security\Core\Exception\AuthenticationException; +use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; use Symfony\Component\Security\Http\Firewall\BasicAuthenticationListener; class BasicAuthenticationListenerTest extends TestCase @@ -29,9 +35,9 @@ public function testHandleWithValidUsernameAndPasswordServerParameters() 'PHP_AUTH_PW' => 'ThePassword', ]); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') @@ -43,7 +49,7 @@ public function testHandleWithValidUsernameAndPasswordServerParameters() ->with($this->equalTo($token)) ; - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $authenticationManager ->expects($this->once()) ->method('authenticate') @@ -55,10 +61,10 @@ public function testHandleWithValidUsernameAndPasswordServerParameters() $tokenStorage, $authenticationManager, 'TheProviderKey', - $this->getMockBuilder(\Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface::class)->getMock() + $this->createMock(AuthenticationEntryPointInterface::class) ); - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') @@ -75,7 +81,7 @@ public function testHandleWhenAuthenticationFails() 'PHP_AUTH_PW' => 'ThePassword', ]); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') @@ -88,22 +94,22 @@ public function testHandleWhenAuthenticationFails() $response = new Response(); - $authenticationEntryPoint = $this->getMockBuilder(\Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface::class)->getMock(); + $authenticationEntryPoint = $this->createMock(AuthenticationEntryPointInterface::class); $authenticationEntryPoint ->expects($this->any()) ->method('start') - ->with($this->equalTo($request), $this->isInstanceOf(\Symfony\Component\Security\Core\Exception\AuthenticationException::class)) + ->with($this->equalTo($request), $this->isInstanceOf(AuthenticationException::class)) ->willReturn($response) ; $listener = new BasicAuthenticationListener( $tokenStorage, - new AuthenticationProviderManager([$this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface::class)->getMock()]), + new AuthenticationProviderManager([$this->createMock(AuthenticationProviderInterface::class)]), 'TheProviderKey', $authenticationEntryPoint ); - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') @@ -122,7 +128,7 @@ public function testHandleWithNoUsernameServerParameter() { $request = new Request(); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->never()) ->method('getToken') @@ -130,12 +136,12 @@ public function testHandleWithNoUsernameServerParameter() $listener = new BasicAuthenticationListener( $tokenStorage, - $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(), + $this->createMock(AuthenticationManagerInterface::class), 'TheProviderKey', - $this->getMockBuilder(\Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface::class)->getMock() + $this->createMock(AuthenticationEntryPointInterface::class) ); - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') @@ -151,14 +157,14 @@ public function testHandleWithASimilarAuthenticatedToken() $token = new UsernamePasswordToken('TheUsername', 'ThePassword', 'TheProviderKey', ['ROLE_FOO']); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') ->willReturn($token) ; - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $authenticationManager ->expects($this->never()) ->method('authenticate') @@ -168,10 +174,10 @@ public function testHandleWithASimilarAuthenticatedToken() $tokenStorage, $authenticationManager, 'TheProviderKey', - $this->getMockBuilder(\Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface::class)->getMock() + $this->createMock(AuthenticationEntryPointInterface::class) ); - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') @@ -186,10 +192,10 @@ public function testItRequiresProviderKey() $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('$providerKey must not be empty'); new BasicAuthenticationListener( - $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(), - $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(), + $this->createMock(TokenStorageInterface::class), + $this->createMock(AuthenticationManagerInterface::class), '', - $this->getMockBuilder(\Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface::class)->getMock() + $this->createMock(AuthenticationEntryPointInterface::class) ); } @@ -202,7 +208,7 @@ public function testHandleWithADifferentAuthenticatedToken() $token = new PreAuthenticatedToken('TheUser', 'TheCredentials', 'TheProviderKey', ['ROLE_FOO']); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage ->expects($this->any()) ->method('getToken') @@ -215,22 +221,22 @@ public function testHandleWithADifferentAuthenticatedToken() $response = new Response(); - $authenticationEntryPoint = $this->getMockBuilder(\Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface::class)->getMock(); + $authenticationEntryPoint = $this->createMock(AuthenticationEntryPointInterface::class); $authenticationEntryPoint ->expects($this->any()) ->method('start') - ->with($this->equalTo($request), $this->isInstanceOf(\Symfony\Component\Security\Core\Exception\AuthenticationException::class)) + ->with($this->equalTo($request), $this->isInstanceOf(AuthenticationException::class)) ->willReturn($response) ; $listener = new BasicAuthenticationListener( $tokenStorage, - new AuthenticationProviderManager([$this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface::class)->getMock()]), + new AuthenticationProviderManager([$this->createMock(AuthenticationProviderInterface::class)]), 'TheProviderKey', $authenticationEntryPoint ); - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/ChannelListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/ChannelListenerTest.php index 7a1170fc66c4..42dd734fca5d 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/ChannelListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/ChannelListenerTest.php @@ -12,22 +12,25 @@ namespace Symfony\Component\Security\Http\Tests\Firewall; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\Security\Http\AccessMapInterface; +use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; use Symfony\Component\Security\Http\Firewall\ChannelListener; class ChannelListenerTest extends TestCase { public function testHandleWithNotSecuredRequestAndHttpChannel() { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->disableOriginalConstructor()->disableOriginalClone()->getMock(); + $request = $this->createMock(Request::class); $request ->expects($this->any()) ->method('isSecure') ->willReturn(false) ; - $accessMap = $this->getMockBuilder(\Symfony\Component\Security\Http\AccessMapInterface::class)->getMock(); + $accessMap = $this->createMock(AccessMapInterface::class); $accessMap ->expects($this->any()) ->method('getPatterns') @@ -35,13 +38,13 @@ public function testHandleWithNotSecuredRequestAndHttpChannel() ->willReturn([[], 'http']) ; - $entryPoint = $this->getMockBuilder(\Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface::class)->getMock(); + $entryPoint = $this->createMock(AuthenticationEntryPointInterface::class); $entryPoint ->expects($this->never()) ->method('start') ; - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') @@ -58,14 +61,14 @@ public function testHandleWithNotSecuredRequestAndHttpChannel() public function testHandleWithSecuredRequestAndHttpsChannel() { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->disableOriginalConstructor()->disableOriginalClone()->getMock(); + $request = $this->createMock(Request::class); $request ->expects($this->any()) ->method('isSecure') ->willReturn(true) ; - $accessMap = $this->getMockBuilder(\Symfony\Component\Security\Http\AccessMapInterface::class)->getMock(); + $accessMap = $this->createMock(AccessMapInterface::class); $accessMap ->expects($this->any()) ->method('getPatterns') @@ -73,13 +76,13 @@ public function testHandleWithSecuredRequestAndHttpsChannel() ->willReturn([[], 'https']) ; - $entryPoint = $this->getMockBuilder(\Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface::class)->getMock(); + $entryPoint = $this->createMock(AuthenticationEntryPointInterface::class); $entryPoint ->expects($this->never()) ->method('start') ; - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') @@ -96,7 +99,7 @@ public function testHandleWithSecuredRequestAndHttpsChannel() public function testHandleWithNotSecuredRequestAndHttpsChannel() { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->disableOriginalConstructor()->disableOriginalClone()->getMock(); + $request = $this->createMock(Request::class); $request ->expects($this->any()) ->method('isSecure') @@ -105,7 +108,7 @@ public function testHandleWithNotSecuredRequestAndHttpsChannel() $response = new Response(); - $accessMap = $this->getMockBuilder(\Symfony\Component\Security\Http\AccessMapInterface::class)->getMock(); + $accessMap = $this->createMock(AccessMapInterface::class); $accessMap ->expects($this->any()) ->method('getPatterns') @@ -113,7 +116,7 @@ public function testHandleWithNotSecuredRequestAndHttpsChannel() ->willReturn([[], 'https']) ; - $entryPoint = $this->getMockBuilder(\Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface::class)->getMock(); + $entryPoint = $this->createMock(AuthenticationEntryPointInterface::class); $entryPoint ->expects($this->once()) ->method('start') @@ -121,7 +124,7 @@ public function testHandleWithNotSecuredRequestAndHttpsChannel() ->willReturn($response) ; - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') @@ -139,7 +142,7 @@ public function testHandleWithNotSecuredRequestAndHttpsChannel() public function testHandleWithSecuredRequestAndHttpChannel() { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->disableOriginalConstructor()->disableOriginalClone()->getMock(); + $request = $this->createMock(Request::class); $request ->expects($this->any()) ->method('isSecure') @@ -148,7 +151,7 @@ public function testHandleWithSecuredRequestAndHttpChannel() $response = new Response(); - $accessMap = $this->getMockBuilder(\Symfony\Component\Security\Http\AccessMapInterface::class)->getMock(); + $accessMap = $this->createMock(AccessMapInterface::class); $accessMap ->expects($this->any()) ->method('getPatterns') @@ -156,7 +159,7 @@ public function testHandleWithSecuredRequestAndHttpChannel() ->willReturn([[], 'http']) ; - $entryPoint = $this->getMockBuilder(\Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface::class)->getMock(); + $entryPoint = $this->createMock(AuthenticationEntryPointInterface::class); $entryPoint ->expects($this->once()) ->method('start') @@ -164,7 +167,7 @@ public function testHandleWithSecuredRequestAndHttpChannel() ->willReturn($response) ; - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/ContextListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/ContextListenerTest.php index b90ed57a2836..3f308dbecf5d 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/ContextListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/ContextListenerTest.php @@ -46,7 +46,7 @@ public function testItRequiresContextKey() $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('$contextKey must not be empty'); new ContextListener( - $this->getMockBuilder(TokenStorageInterface::class)->getMock(), + $this->createMock(TokenStorageInterface::class), [], '' ); @@ -109,7 +109,7 @@ public function testOnKernelResponseWithoutSession() $request->setSession($session); $event = new ResponseEvent( - $this->getMockBuilder(HttpKernelInterface::class)->getMock(), + $this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST, new Response() @@ -128,7 +128,7 @@ public function testOnKernelResponseWithoutSessionNorToken() $request->setSession($session); $event = new ResponseEvent( - $this->getMockBuilder(HttpKernelInterface::class)->getMock(), + $this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST, new Response() @@ -145,12 +145,10 @@ public function testOnKernelResponseWithoutSessionNorToken() */ public function testInvalidTokenInSession($token) { - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); - $event = $this->getMockBuilder(RequestEvent::class) - ->disableOriginalConstructor() - ->getMock(); - $request = $this->getMockBuilder(Request::class)->getMock(); - $session = $this->getMockBuilder(SessionInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); + $event = $this->createMock(RequestEvent::class); + $request = $this->createMock(Request::class); + $session = $this->createMock(SessionInterface::class); $event->expects($this->any()) ->method('getRequest') @@ -186,11 +184,9 @@ public function provideInvalidToken() public function testHandleAddsKernelResponseListener() { - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); - $dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); - $event = $this->getMockBuilder(RequestEvent::class) - ->disableOriginalConstructor() - ->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); + $dispatcher = $this->createMock(EventDispatcherInterface::class); + $event = $this->createMock(RequestEvent::class); $listener = new ContextListener($tokenStorage, [], 'key123', null, $dispatcher); @@ -199,7 +195,7 @@ public function testHandleAddsKernelResponseListener() ->willReturn(true); $event->expects($this->any()) ->method('getRequest') - ->willReturn($this->getMockBuilder(Request::class)->getMock()); + ->willReturn($this->createMock(Request::class)); $dispatcher->expects($this->once()) ->method('addListener') @@ -210,13 +206,13 @@ public function testHandleAddsKernelResponseListener() public function testOnKernelResponseListenerRemovesItself() { - $session = $this->getMockBuilder(SessionInterface::class)->getMock(); - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); - $dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); + $session = $this->createMock(SessionInterface::class); + $tokenStorage = $this->createMock(TokenStorageInterface::class); + $dispatcher = $this->createMock(EventDispatcherInterface::class); $listener = new ContextListener($tokenStorage, [], 'key123', null, $dispatcher); - $request = $this->getMockBuilder(Request::class)->getMock(); + $request = $this->createMock(Request::class); $request->expects($this->any()) ->method('hasSession') ->willReturn(true); @@ -235,15 +231,13 @@ public function testOnKernelResponseListenerRemovesItself() public function testHandleRemovesTokenIfNoPreviousSessionWasFound() { - $request = $this->getMockBuilder(Request::class)->getMock(); + $request = $this->createMock(Request::class); $request->expects($this->any())->method('hasPreviousSession')->willReturn(false); - $event = $this->getMockBuilder(RequestEvent::class) - ->disableOriginalConstructor() - ->getMock(); + $event = $this->createMock(RequestEvent::class); $event->expects($this->any())->method('getRequest')->willReturn($request); - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage->expects($this->once())->method('setToken')->with(null); $listener = new ContextListener($tokenStorage, [], 'key123'); @@ -339,7 +333,7 @@ public function testDeauthenticatedEvent() }); $listener = new ContextListener($tokenStorage, [new NotSupportingUserProvider(true), new NotSupportingUserProvider(false), new SupportingUserProvider($refreshedUser)], 'context_key', null, $eventDispatcher); - $listener(new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $request, HttpKernelInterface::MASTER_REQUEST)); + $listener(new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST)); $this->assertNull($tokenStorage->getToken()); } @@ -359,7 +353,7 @@ public function testWithPreviousNotStartedSession() $tokenStorage = new TokenStorage(); $listener = new ContextListener($tokenStorage, [], 'context_key', null, null, null, [$tokenStorage, 'getToken']); - $listener(new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $request, HttpKernelInterface::MASTER_REQUEST)); + $listener(new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST)); $this->assertSame($usageIndex, $session->getUsageIndex()); } @@ -389,7 +383,7 @@ protected function runSessionOnKernelResponse($newToken, $original = null) $usageIndex = method_exists(Request::class, 'getPreferredFormat') ? $session->getUsageIndex() : null; $event = new ResponseEvent( - $this->getMockBuilder(HttpKernelInterface::class)->getMock(), + $this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST, new Response() @@ -439,7 +433,7 @@ private function handleEventWithPreviousSession($userProviders, UserInterface $u if ($rememberMeServices) { $listener->setRememberMeServices($rememberMeServices); } - $listener(new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $request, HttpKernelInterface::MASTER_REQUEST)); + $listener(new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST)); if (null !== $usageIndex) { if (null !== $user) { diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/ExceptionListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/ExceptionListenerTest.php index aa2d657d0488..3c6020b27d62 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/ExceptionListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/ExceptionListenerTest.php @@ -19,6 +19,7 @@ use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Core\Exception\LogoutException; @@ -77,7 +78,7 @@ public function testExceptionWhenEntryPointReturnsBadValue() { $event = $this->createEvent(new AuthenticationException()); - $entryPoint = $this->getMockBuilder(AuthenticationEntryPointInterface::class)->getMock(); + $entryPoint = $this->createMock(AuthenticationEntryPointInterface::class); $entryPoint->expects($this->once())->method('start')->willReturn('NOT A RESPONSE'); $listener = $this->createExceptionListener(null, null, null, $entryPoint); @@ -106,12 +107,12 @@ public function testAccessDeniedExceptionFullFledgedAndWithoutAccessDeniedHandle */ public function testAccessDeniedExceptionFullFledgedAndWithoutAccessDeniedHandlerAndWithErrorPage(\Exception $exception, \Exception $eventException = null) { - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); $kernel->expects($this->once())->method('handle')->willReturn(new Response('Unauthorized', 401)); $event = $this->createEvent($exception, $kernel); - $httpUtils = $this->getMockBuilder(HttpUtils::class)->getMock(); + $httpUtils = $this->createMock(HttpUtils::class); $httpUtils->expects($this->once())->method('createRequest')->willReturn(Request::create('/error')); $listener = $this->createExceptionListener(null, $this->createTrustResolver(true), $httpUtils, null, '/error'); @@ -131,7 +132,7 @@ public function testAccessDeniedExceptionFullFledgedAndWithAccessDeniedHandlerAn { $event = $this->createEvent($exception); - $accessDeniedHandler = $this->getMockBuilder(AccessDeniedHandlerInterface::class)->getMock(); + $accessDeniedHandler = $this->createMock(AccessDeniedHandlerInterface::class); $accessDeniedHandler->expects($this->once())->method('handle')->willReturn(new Response('error')); $listener = $this->createExceptionListener(null, $this->createTrustResolver(true), null, null, null, $accessDeniedHandler); @@ -148,8 +149,8 @@ public function testAccessDeniedExceptionNotFullFledged(\Exception $exception, \ { $event = $this->createEvent($exception); - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); - $tokenStorage->expects($this->once())->method('getToken')->willReturn($this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()); + $tokenStorage = $this->createMock(TokenStorageInterface::class); + $tokenStorage->expects($this->once())->method('getToken')->willReturn($this->createMock(TokenInterface::class)); $listener = $this->createExceptionListener($tokenStorage, $this->createTrustResolver(false), null, $this->createEntryPoint()); $listener->onKernelException($event); @@ -182,7 +183,7 @@ public function getAccessDeniedExceptionProvider() private function createEntryPoint(Response $response = null) { - $entryPoint = $this->getMockBuilder(AuthenticationEntryPointInterface::class)->getMock(); + $entryPoint = $this->createMock(AuthenticationEntryPointInterface::class); $entryPoint->expects($this->once())->method('start')->willReturn($response ?: new Response('OK')); return $entryPoint; @@ -190,7 +191,7 @@ private function createEntryPoint(Response $response = null) private function createTrustResolver($fullFledged) { - $trustResolver = $this->getMockBuilder(AuthenticationTrustResolverInterface::class)->getMock(); + $trustResolver = $this->createMock(AuthenticationTrustResolverInterface::class); $trustResolver->expects($this->once())->method('isFullFledged')->willReturn($fullFledged); return $trustResolver; @@ -199,7 +200,7 @@ private function createTrustResolver($fullFledged) private function createEvent(\Exception $exception, $kernel = null) { if (null === $kernel) { - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $kernel = $this->createMock(HttpKernelInterface::class); } return new ExceptionEvent($kernel, Request::create('/'), HttpKernelInterface::MASTER_REQUEST, $exception); @@ -208,9 +209,9 @@ private function createEvent(\Exception $exception, $kernel = null) private function createExceptionListener(TokenStorageInterface $tokenStorage = null, AuthenticationTrustResolverInterface $trustResolver = null, HttpUtils $httpUtils = null, AuthenticationEntryPointInterface $authenticationEntryPoint = null, $errorPage = null, AccessDeniedHandlerInterface $accessDeniedHandler = null) { return new ExceptionListener( - $tokenStorage ?: $this->getMockBuilder(TokenStorageInterface::class)->getMock(), - $trustResolver ?: $this->getMockBuilder(AuthenticationTrustResolverInterface::class)->getMock(), - $httpUtils ?: $this->getMockBuilder(HttpUtils::class)->getMock(), + $tokenStorage ?: $this->createMock(TokenStorageInterface::class), + $trustResolver ?: $this->createMock(AuthenticationTrustResolverInterface::class), + $httpUtils ?: $this->createMock(HttpUtils::class), 'key', $authenticationEntryPoint, $errorPage, diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.php index 1b81fc053c0a..7f3c8f90bb33 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.php @@ -15,7 +15,14 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; +use Symfony\Component\Security\Core\Exception\LogoutException; +use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Symfony\Component\Security\Http\Firewall\LogoutListener; +use Symfony\Component\Security\Http\HttpUtils; +use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface; +use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface; class LogoutListenerTest extends TestCase { @@ -147,7 +154,7 @@ public function testSuccessHandlerReturnsNonResponse() public function testCsrfValidationFails() { - $this->expectException(\Symfony\Component\Security\Core\Exception\LogoutException::class); + $this->expectException(LogoutException::class); $tokenManager = $this->getTokenManager(); [$listener, , $httpUtils, $options] = $this->getListener(null, $tokenManager); @@ -170,19 +177,17 @@ public function testCsrfValidationFails() private function getTokenManager() { - return $this->getMockBuilder(\Symfony\Component\Security\Csrf\CsrfTokenManagerInterface::class)->getMock(); + return $this->createMock(CsrfTokenManagerInterface::class); } private function getTokenStorage() { - return $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + return $this->createMock(TokenStorageInterface::class); } private function getGetResponseEvent() { - $event = $this->getMockBuilder(RequestEvent::class) - ->disableOriginalConstructor() - ->getMock(); + $event = $this->createMock(RequestEvent::class); $event->expects($this->any()) ->method('getRequest') @@ -193,14 +198,12 @@ private function getGetResponseEvent() private function getHandler() { - return $this->getMockBuilder(\Symfony\Component\Security\Http\Logout\LogoutHandlerInterface::class)->getMock(); + return $this->createMock(LogoutHandlerInterface::class); } private function getHttpUtils() { - return $this->getMockBuilder(\Symfony\Component\Security\Http\HttpUtils::class) - ->disableOriginalConstructor() - ->getMock(); + return $this->createMock(HttpUtils::class); } private function getListener($successHandler = null, $tokenManager = null) @@ -223,11 +226,11 @@ private function getListener($successHandler = null, $tokenManager = null) private function getSuccessHandler() { - return $this->getMockBuilder(\Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface::class)->getMock(); + return $this->createMock(LogoutSuccessHandlerInterface::class); } private function getToken() { - return $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + return $this->createMock(TokenInterface::class); } } diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/RememberMeListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/RememberMeListenerTest.php index 8367a233d293..88648c301ab5 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/RememberMeListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/RememberMeListenerTest.php @@ -12,13 +12,19 @@ namespace Symfony\Component\Security\Http\Tests\Firewall; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\Event\ResponseEvent; use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; +use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; use Symfony\Component\Security\Http\Firewall\RememberMeListener; +use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface; use Symfony\Component\Security\Http\SecurityEvents; use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; @@ -32,7 +38,7 @@ public function testOnCoreSecurityDoesNotTryToPopulateNonEmptyTokenStorage() $tokenStorage ->expects($this->any()) ->method('getToken') - ->willReturn($this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()) + ->willReturn($this->createMock(TokenInterface::class)) ; $tokenStorage @@ -79,7 +85,7 @@ public function testOnCoreSecurityIgnoresAuthenticationExceptionThrownByAuthenti $service ->expects($this->once()) ->method('autoLogin') - ->willReturn($this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()) + ->willReturn($this->createMock(TokenInterface::class)) ; $service @@ -114,7 +120,7 @@ public function testOnCoreSecurityIgnoresAuthenticationOptionallyRethrowsExcepti $service ->expects($this->once()) ->method('autoLogin') - ->willReturn($this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()) + ->willReturn($this->createMock(TokenInterface::class)) ; $service @@ -176,7 +182,7 @@ public function testOnCoreSecurity() ->willReturn(null) ; - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $service ->expects($this->once()) ->method('autoLogin') @@ -210,7 +216,7 @@ public function testSessionStrategy() ->willReturn(null) ; - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $service ->expects($this->once()) ->method('autoLogin') @@ -229,7 +235,7 @@ public function testSessionStrategy() ->willReturn($token) ; - $session = $this->getMockBuilder(SessionInterface::class)->getMock(); + $session = $this->createMock(SessionInterface::class); $session ->expects($this->once()) ->method('isStarted') @@ -260,7 +266,7 @@ public function testSessionIsMigratedByDefault() ->willReturn(null) ; - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $service ->expects($this->once()) ->method('autoLogin') @@ -279,7 +285,7 @@ public function testSessionIsMigratedByDefault() ->willReturn($token) ; - $session = $this->getMockBuilder(SessionInterface::class)->getMock(); + $session = $this->createMock(SessionInterface::class); $session ->expects($this->once()) ->method('isStarted') @@ -308,7 +314,7 @@ public function testOnCoreSecurityInteractiveLoginEventIsDispatchedIfDispatcherI ->willReturn(null) ; - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $service ->expects($this->once()) ->method('autoLogin') @@ -333,7 +339,7 @@ public function testOnCoreSecurityInteractiveLoginEventIsDispatchedIfDispatcherI ->expects($this->once()) ->method('dispatch') ->with( - $this->isInstanceOf(\Symfony\Component\Security\Http\Event\InteractiveLoginEvent::class), + $this->isInstanceOf(InteractiveLoginEvent::class), SecurityEvents::INTERACTIVE_LOGIN ) ; @@ -359,7 +365,7 @@ protected function getGetResponseEvent(Request $request = null): RequestEvent protected function getResponseEvent(): ResponseEvent { - return $this->getMockBuilder(ResponseEvent::class)->disableOriginalConstructor()->getMock(); + return $this->createMock(ResponseEvent::class); } protected function getListener($withDispatcher = false, $catchExceptions = true, $withSessionStrategy = false) @@ -379,31 +385,31 @@ protected function getListener($withDispatcher = false, $catchExceptions = true, protected function getLogger() { - return $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + return $this->createMock(LoggerInterface::class); } protected function getManager() { - return $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + return $this->createMock(AuthenticationManagerInterface::class); } protected function getService() { - return $this->getMockBuilder(\Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface::class)->getMock(); + return $this->createMock(RememberMeServicesInterface::class); } protected function getTokenStorage() { - return $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + return $this->createMock(TokenStorageInterface::class); } protected function getDispatcher() { - return $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); + return $this->createMock(EventDispatcherInterface::class); } private function getSessionStrategy() { - return $this->getMockBuilder(SessionAuthenticationStrategyInterface::class)->getMock(); + return $this->createMock(SessionAuthenticationStrategyInterface::class); } } diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/RemoteUserAuthenticationListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/RemoteUserAuthenticationListenerTest.php index 888d67254737..a50f99bd94e3 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/RemoteUserAuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/RemoteUserAuthenticationListenerTest.php @@ -13,6 +13,9 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Exception\BadCredentialsException; use Symfony\Component\Security\Http\Firewall\RemoteUserAuthenticationListener; class RemoteUserAuthenticationListenerTest extends TestCase @@ -25,9 +28,9 @@ public function testGetPreAuthenticatedData() $request = new Request([], [], [], [], [], $serverVars); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $listener = new RemoteUserAuthenticationListener( $tokenStorage, @@ -44,12 +47,12 @@ public function testGetPreAuthenticatedData() public function testGetPreAuthenticatedDataNoUser() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $request = new Request([], [], [], [], [], []); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $listener = new RemoteUserAuthenticationListener( $tokenStorage, @@ -70,9 +73,9 @@ public function testGetPreAuthenticatedDataWithDifferentKeys() $request = new Request([], [], [], [], [], [ 'TheUserKey' => 'TheUser', ]); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $listener = new RemoteUserAuthenticationListener( $tokenStorage, diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/SimplePreAuthenticationListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/SimplePreAuthenticationListenerTest.php index 82265c292ae9..23ee13a81698 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/SimplePreAuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/SimplePreAuthenticationListenerTest.php @@ -12,9 +12,15 @@ namespace Symfony\Component\Security\Http\Tests\Firewall; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; +use Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface; use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; use Symfony\Component\Security\Http\Firewall\SimplePreAuthenticationListener; use Symfony\Component\Security\Http\SecurityEvents; @@ -47,7 +53,7 @@ public function testHandle() ->willReturn($this->token) ; - $simpleAuthenticator = $this->getMockBuilder(\Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface::class)->getMock(); + $simpleAuthenticator = $this->createMock(SimplePreAuthenticatorInterface::class); $simpleAuthenticator ->expects($this->once()) ->method('createToken') @@ -84,7 +90,7 @@ public function testHandlecatchAuthenticationException() ->with($this->equalTo(null)) ; - $simpleAuthenticator = $this->getMockBuilder(\Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface::class)->getMock(); + $simpleAuthenticator = $this->createMock(SimplePreAuthenticatorInterface::class); $simpleAuthenticator ->expects($this->once()) ->method('createToken') @@ -99,25 +105,21 @@ public function testHandlecatchAuthenticationException() protected function setUp(): void { - $this->authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager::class) - ->disableOriginalConstructor() - ->getMock() - ; - - $this->dispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class)->getMock(); + $this->authenticationManager = $this->createMock(AuthenticationProviderManager::class); + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); $this->request = new Request([], [], [], [], [], []); - $this->event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $this->event = $this->createMock(RequestEvent::class); $this->event ->expects($this->any()) ->method('getRequest') ->willReturn($this->request) ; - $this->logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); - $this->tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); - $this->token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $this->logger = $this->createMock(LoggerInterface::class); + $this->tokenStorage = $this->createMock(TokenStorageInterface::class); + $this->token = $this->createMock(TokenInterface::class); } protected function tearDown(): void diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php index 45d6a77bb485..18e5c415d5ec 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php @@ -12,15 +12,22 @@ namespace Symfony\Component\Security\Http\Tests\Firewall; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; +use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface; +use Symfony\Component\Security\Core\Exception\AccessDeniedException; +use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\Role\SwitchUserRole; use Symfony\Component\Security\Core\User\User; +use Symfony\Component\Security\Core\User\UserCheckerInterface; +use Symfony\Component\Security\Core\User\UserInterface; +use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Http\Event\SwitchUserEvent; use Symfony\Component\Security\Http\Firewall\SwitchUserListener; use Symfony\Component\Security\Http\SecurityEvents; @@ -43,11 +50,11 @@ class SwitchUserListenerTest extends TestCase protected function setUp(): void { $this->tokenStorage = new TokenStorage(); - $this->userProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserProviderInterface::class)->getMock(); - $this->userChecker = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserCheckerInterface::class)->getMock(); - $this->accessDecisionManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface::class)->getMock(); + $this->userProvider = $this->createMock(UserProviderInterface::class); + $this->userChecker = $this->createMock(UserCheckerInterface::class); + $this->accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class); $this->request = new Request(); - $this->event = new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $this->request, HttpKernelInterface::MASTER_REQUEST); + $this->event = new RequestEvent($this->createMock(HttpKernelInterface::class), $this->request, HttpKernelInterface::MASTER_REQUEST); } public function testProviderKeyIsRequired() @@ -68,7 +75,7 @@ public function testEventIsIgnoredIfUsernameIsNotPassedWithTheRequest() public function testExitUserThrowsAuthenticationExceptionIfNoCurrentToken() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException::class); + $this->expectException(AuthenticationCredentialsNotFoundException::class); $this->tokenStorage->setToken(null); $this->request->query->set('_switch_user', '_exit'); $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager); @@ -77,7 +84,7 @@ public function testExitUserThrowsAuthenticationExceptionIfNoCurrentToken() public function testExitUserThrowsAuthenticationExceptionIfOriginalTokenCannotBeFound() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException::class); + $this->expectException(AuthenticationCredentialsNotFoundException::class); $token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']); $this->tokenStorage->setToken($token); @@ -99,7 +106,7 @@ public function testExitUserUpdatesToken() $this->assertSame([], $this->request->query->all()); $this->assertSame('', $this->request->server->get('QUERY_STRING')); - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\RedirectResponse::class, $this->event->getResponse()); + $this->assertInstanceOf(RedirectResponse::class, $this->event->getResponse()); $this->assertSame($this->request->getUri(), $this->event->getResponse()->getTargetUrl()); $this->assertSame($originalToken, $this->tokenStorage->getToken()); } @@ -122,8 +129,8 @@ public function testExitUserBasedOnSwitchUserRoleUpdatesToken() public function testExitUserDispatchesEventWithRefreshedUser() { - $originalUser = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); - $refreshedUser = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $originalUser = $this->createMock(UserInterface::class); + $refreshedUser = $this->createMock(UserInterface::class); $this ->userProvider ->expects($this->any()) @@ -134,7 +141,7 @@ public function testExitUserDispatchesEventWithRefreshedUser() $this->tokenStorage->setToken(new SwitchUserToken('username', '', 'key', [new SwitchUserRole('ROLE_PREVIOUS', $originalToken, false)], $originalToken)); $this->request->query->set('_switch_user', SwitchUserListener::EXIT_VALUE); - $dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); + $dispatcher = $this->createMock(EventDispatcherInterface::class); $dispatcher ->expects($this->once()) ->method('dispatch') @@ -161,7 +168,7 @@ public function testExitUserDoesNotDispatchEventWithStringUser() $this->tokenStorage->setToken(new SwitchUserToken('username', '', 'key', [new SwitchUserRole('ROLE_PREVIOUS', $originalToken, false)], $originalToken)); $this->request->query->set('_switch_user', SwitchUserListener::EXIT_VALUE); - $dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); + $dispatcher = $this->createMock(EventDispatcherInterface::class); $dispatcher ->expects($this->never()) ->method('dispatch') @@ -173,7 +180,7 @@ public function testExitUserDoesNotDispatchEventWithStringUser() public function testSwitchUserIsDisallowed() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AccessDeniedException::class); + $this->expectException(AccessDeniedException::class); $token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']); $user = new User('username', 'password', []); @@ -195,7 +202,7 @@ public function testSwitchUserIsDisallowed() public function testSwitchUserTurnsAuthenticationExceptionTo403() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AccessDeniedException::class); + $this->expectException(AccessDeniedException::class); $token = new UsernamePasswordToken('username', '', 'key', ['ROLE_ALLOWED_TO_SWITCH']); $this->tokenStorage->setToken($token); @@ -350,7 +357,7 @@ public function testSwitchUserWithReplacedToken() ->withConsecutive(['kuba']) ->will($this->onConsecutiveCalls($user, $this->throwException(new UsernameNotFoundException()))); - $dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); + $dispatcher = $this->createMock(EventDispatcherInterface::class); $dispatcher ->expects($this->once()) ->method('dispatch') @@ -374,7 +381,7 @@ public function testSwitchUserWithReplacedToken() public function testSwitchUserThrowsAuthenticationExceptionIfNoCurrentToken() { - $this->expectException(\Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException::class); + $this->expectException(AuthenticationCredentialsNotFoundException::class); $this->tokenStorage->setToken(null); $this->request->query->set('_switch_user', 'username'); $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager); diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordFormAuthenticationListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordFormAuthenticationListenerTest.php index ffdec63b2723..c1299fd1fe9a 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordFormAuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordFormAuthenticationListenerTest.php @@ -15,15 +15,22 @@ use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; +use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Security; +use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface; use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler; use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler; use Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener; use Symfony\Component\Security\Http\HttpUtils; use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy; +use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface; class UsernamePasswordFormAuthenticationListenerTest extends TestCase { @@ -33,9 +40,9 @@ class UsernamePasswordFormAuthenticationListenerTest extends TestCase public function testHandleWhenUsernameLength($username, $ok) { $request = Request::create('/login_check', 'POST', ['_username' => $username]); - $request->setSession($this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\SessionInterface::class)->getMock()); + $request->setSession($this->createMock(SessionInterface::class)); - $httpUtils = $this->getMockBuilder(HttpUtils::class)->getMock(); + $httpUtils = $this->createMock(HttpUtils::class); $httpUtils ->expects($this->any()) ->method('checkRequestPath') @@ -46,14 +53,14 @@ public function testHandleWhenUsernameLength($username, $ok) ->willReturn(new RedirectResponse('/hello')) ; - $failureHandler = $this->getMockBuilder(\Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface::class)->getMock(); + $failureHandler = $this->createMock(AuthenticationFailureHandlerInterface::class); $failureHandler ->expects($ok ? $this->never() : $this->once()) ->method('onAuthenticationFailure') ->willReturn(new Response()) ; - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager::class)->disableOriginalConstructor()->getMock(); + $authenticationManager = $this->createMock(AuthenticationProviderManager::class); $authenticationManager ->expects($ok ? $this->once() : $this->never()) ->method('authenticate') @@ -61,9 +68,9 @@ public function testHandleWhenUsernameLength($username, $ok) ; $listener = new UsernamePasswordFormAuthenticationListener( - $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(), + $this->createMock(TokenStorageInterface::class), $authenticationManager, - $this->getMockBuilder(\Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface::class)->getMock(), + $this->createMock(SessionAuthenticationStrategyInterface::class), $httpUtils, 'TheProviderKey', new DefaultAuthenticationSuccessHandler($httpUtils), @@ -71,7 +78,7 @@ public function testHandleWhenUsernameLength($username, $ok) ['require_previous_session' => false] ); - $event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock(); + $event = $this->createMock(RequestEvent::class); $event ->expects($this->any()) ->method('getRequest') @@ -86,21 +93,21 @@ public function testHandleWhenUsernameLength($username, $ok) */ public function testHandleNonStringUsernameWithArray($postOnly) { - $this->expectException(\Symfony\Component\HttpKernel\Exception\BadRequestHttpException::class); + $this->expectException(BadRequestHttpException::class); $this->expectExceptionMessage('The key "_username" must be a string, "array" given.'); $request = Request::create('/login_check', 'POST', ['_username' => []]); - $request->setSession($this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\SessionInterface::class)->getMock()); + $request->setSession($this->createMock(SessionInterface::class)); $listener = new UsernamePasswordFormAuthenticationListener( new TokenStorage(), - $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(), + $this->createMock(AuthenticationManagerInterface::class), new SessionAuthenticationStrategy(SessionAuthenticationStrategy::NONE), $httpUtils = new HttpUtils(), 'foo', new DefaultAuthenticationSuccessHandler($httpUtils), - new DefaultAuthenticationFailureHandler($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $httpUtils), + new DefaultAuthenticationFailureHandler($this->createMock(HttpKernelInterface::class), $httpUtils), ['require_previous_session' => false, 'post_only' => $postOnly] ); - $event = new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $request, HttpKernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST); $listener($event); } @@ -109,21 +116,21 @@ public function testHandleNonStringUsernameWithArray($postOnly) */ public function testHandleNonStringUsernameWithInt($postOnly) { - $this->expectException(\Symfony\Component\HttpKernel\Exception\BadRequestHttpException::class); + $this->expectException(BadRequestHttpException::class); $this->expectExceptionMessage('The key "_username" must be a string, "integer" given.'); $request = Request::create('/login_check', 'POST', ['_username' => 42]); - $request->setSession($this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\SessionInterface::class)->getMock()); + $request->setSession($this->createMock(SessionInterface::class)); $listener = new UsernamePasswordFormAuthenticationListener( new TokenStorage(), - $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(), + $this->createMock(AuthenticationManagerInterface::class), new SessionAuthenticationStrategy(SessionAuthenticationStrategy::NONE), $httpUtils = new HttpUtils(), 'foo', new DefaultAuthenticationSuccessHandler($httpUtils), - new DefaultAuthenticationFailureHandler($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $httpUtils), + new DefaultAuthenticationFailureHandler($this->createMock(HttpKernelInterface::class), $httpUtils), ['require_previous_session' => false, 'post_only' => $postOnly] ); - $event = new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $request, HttpKernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST); $listener($event); } @@ -132,21 +139,21 @@ public function testHandleNonStringUsernameWithInt($postOnly) */ public function testHandleNonStringUsernameWithObject($postOnly) { - $this->expectException(\Symfony\Component\HttpKernel\Exception\BadRequestHttpException::class); + $this->expectException(BadRequestHttpException::class); $this->expectExceptionMessage('The key "_username" must be a string, "object" given.'); $request = Request::create('/login_check', 'POST', ['_username' => new \stdClass()]); - $request->setSession($this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\SessionInterface::class)->getMock()); + $request->setSession($this->createMock(SessionInterface::class)); $listener = new UsernamePasswordFormAuthenticationListener( new TokenStorage(), - $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(), + $this->createMock(AuthenticationManagerInterface::class), new SessionAuthenticationStrategy(SessionAuthenticationStrategy::NONE), $httpUtils = new HttpUtils(), 'foo', new DefaultAuthenticationSuccessHandler($httpUtils), - new DefaultAuthenticationFailureHandler($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $httpUtils), + new DefaultAuthenticationFailureHandler($this->createMock(HttpKernelInterface::class), $httpUtils), ['require_previous_session' => false, 'post_only' => $postOnly] ); - $event = new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $request, HttpKernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST); $listener($event); } @@ -155,25 +162,25 @@ public function testHandleNonStringUsernameWithObject($postOnly) */ public function testHandleNonStringUsernameWith__toString($postOnly) { - $usernameClass = $this->getMockBuilder(DummyUserClass::class)->getMock(); + $usernameClass = $this->createMock(DummyUserClass::class); $usernameClass ->expects($this->atLeastOnce()) ->method('__toString') ->willReturn('someUsername'); $request = Request::create('/login_check', 'POST', ['_username' => $usernameClass]); - $request->setSession($this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\SessionInterface::class)->getMock()); + $request->setSession($this->createMock(SessionInterface::class)); $listener = new UsernamePasswordFormAuthenticationListener( new TokenStorage(), - $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(), + $this->createMock(AuthenticationManagerInterface::class), new SessionAuthenticationStrategy(SessionAuthenticationStrategy::NONE), $httpUtils = new HttpUtils(), 'foo', new DefaultAuthenticationSuccessHandler($httpUtils), - new DefaultAuthenticationFailureHandler($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $httpUtils), + new DefaultAuthenticationFailureHandler($this->createMock(HttpKernelInterface::class), $httpUtils), ['require_previous_session' => false, 'post_only' => $postOnly] ); - $event = new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $request, HttpKernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST); $listener($event); } diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordJsonAuthenticationListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordJsonAuthenticationListenerTest.php index d12a30974f96..14befc7322df 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordJsonAuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordJsonAuthenticationListenerTest.php @@ -14,7 +14,9 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; @@ -25,6 +27,7 @@ use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface; use Symfony\Component\Security\Http\Firewall\UsernamePasswordJsonAuthenticationListener; use Symfony\Component\Security\Http\HttpUtils; +use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface; /** * @author Kévin Dunglas @@ -38,16 +41,16 @@ class UsernamePasswordJsonAuthenticationListenerTest extends TestCase private function createListener(array $options = [], $success = true, $matchCheckPath = true) { - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); - $httpUtils = $this->getMockBuilder(HttpUtils::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); + $httpUtils = $this->createMock(HttpUtils::class); $httpUtils ->expects($this->any()) ->method('checkRequestPath') ->willReturn($matchCheckPath) ; - $authenticationManager = $this->getMockBuilder(AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); - $authenticatedToken = $this->getMockBuilder(TokenInterface::class)->getMock(); + $authenticatedToken = $this->createMock(TokenInterface::class); if ($success) { $authenticationManager->method('authenticate')->willReturn($authenticatedToken); @@ -55,9 +58,9 @@ private function createListener(array $options = [], $success = true, $matchChec $authenticationManager->method('authenticate')->willThrowException(new AuthenticationException()); } - $authenticationSuccessHandler = $this->getMockBuilder(AuthenticationSuccessHandlerInterface::class)->getMock(); + $authenticationSuccessHandler = $this->createMock(AuthenticationSuccessHandlerInterface::class); $authenticationSuccessHandler->method('onAuthenticationSuccess')->willReturn(new Response('ok')); - $authenticationFailureHandler = $this->getMockBuilder(AuthenticationFailureHandlerInterface::class)->getMock(); + $authenticationFailureHandler = $this->createMock(AuthenticationFailureHandlerInterface::class); $authenticationFailureHandler->method('onAuthenticationFailure')->willReturn(new Response('ko')); $this->listener = new UsernamePasswordJsonAuthenticationListener($tokenStorage, $authenticationManager, $httpUtils, 'providerKey', $authenticationSuccessHandler, $authenticationFailureHandler, $options); @@ -67,7 +70,7 @@ public function testHandleSuccessIfRequestContentTypeIsJson() { $this->createListener(); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "password": "foo"}'); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); ($this->listener)($event); $this->assertEquals('ok', $event->getResponse()->getContent()); @@ -78,7 +81,7 @@ public function testSuccessIfRequestFormatIsJsonLD() $this->createListener(); $request = new Request([], [], [], [], [], [], '{"username": "dunglas", "password": "foo"}'); $request->setRequestFormat('json-ld'); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); ($this->listener)($event); $this->assertEquals('ok', $event->getResponse()->getContent()); @@ -88,7 +91,7 @@ public function testHandleFailure() { $this->createListener([], false); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "password": "foo"}'); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); ($this->listener)($event); $this->assertEquals('ko', $event->getResponse()->getContent()); @@ -98,7 +101,7 @@ public function testUsePath() { $this->createListener(['username_path' => 'user.login', 'password_path' => 'user.pwd']); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"user": {"login": "dunglas", "pwd": "foo"}}'); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); ($this->listener)($event); $this->assertEquals('ok', $event->getResponse()->getContent()); @@ -106,56 +109,56 @@ public function testUsePath() public function testAttemptAuthenticationNoJson() { - $this->expectException(\Symfony\Component\HttpKernel\Exception\BadRequestHttpException::class); + $this->expectException(BadRequestHttpException::class); $this->expectExceptionMessage('Invalid JSON'); $this->createListener(); $request = new Request(); $request->setRequestFormat('json'); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); ($this->listener)($event); } public function testAttemptAuthenticationNoUsername() { - $this->expectException(\Symfony\Component\HttpKernel\Exception\BadRequestHttpException::class); + $this->expectException(BadRequestHttpException::class); $this->expectExceptionMessage('The key "username" must be provided'); $this->createListener(); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"usr": "dunglas", "password": "foo"}'); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); ($this->listener)($event); } public function testAttemptAuthenticationNoPassword() { - $this->expectException(\Symfony\Component\HttpKernel\Exception\BadRequestHttpException::class); + $this->expectException(BadRequestHttpException::class); $this->expectExceptionMessage('The key "password" must be provided'); $this->createListener(); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "pass": "foo"}'); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); ($this->listener)($event); } public function testAttemptAuthenticationUsernameNotAString() { - $this->expectException(\Symfony\Component\HttpKernel\Exception\BadRequestHttpException::class); + $this->expectException(BadRequestHttpException::class); $this->expectExceptionMessage('The key "username" must be a string.'); $this->createListener(); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": 1, "password": "foo"}'); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); ($this->listener)($event); } public function testAttemptAuthenticationPasswordNotAString() { - $this->expectException(\Symfony\Component\HttpKernel\Exception\BadRequestHttpException::class); + $this->expectException(BadRequestHttpException::class); $this->expectExceptionMessage('The key "password" must be a string.'); $this->createListener(); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "password": 1}'); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); ($this->listener)($event); } @@ -165,7 +168,7 @@ public function testAttemptAuthenticationUsernameTooLong() $this->createListener(); $username = str_repeat('x', Security::MAX_USERNAME_LENGTH + 1); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], sprintf('{"username": "%s", "password": 1}', $username)); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); ($this->listener)($event); $this->assertSame('ko', $event->getResponse()->getContent()); @@ -175,7 +178,7 @@ public function testDoesNotAttemptAuthenticationIfRequestPathDoesNotMatchCheckPa { $this->createListener(['check_path' => '/'], true, false); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json']); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); $event->setResponse(new Response('original')); ($this->listener)($event); @@ -186,7 +189,7 @@ public function testDoesNotAttemptAuthenticationIfRequestContentTypeIsNotJson() { $this->createListener(); $request = new Request([], [], [], [], [], [], '{"username": "dunglas", "password": "foo"}'); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); $event->setResponse(new Response('original')); ($this->listener)($event); @@ -197,7 +200,7 @@ public function testAttemptAuthenticationIfRequestPathMatchesCheckPath() { $this->createListener(['check_path' => '/']); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "password": "foo"}'); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); ($this->listener)($event); $this->assertSame('ok', $event->getResponse()->getContent()); @@ -208,7 +211,7 @@ public function testNoErrorOnMissingSessionStrategy() $this->createListener(); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "password": "foo"}'); $this->configurePreviousSession($request); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); ($this->listener)($event); $this->assertEquals('ok', $event->getResponse()->getContent()); @@ -219,9 +222,9 @@ public function testMigratesViaSessionStrategy() $this->createListener(); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "password": "foo"}'); $this->configurePreviousSession($request); - $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(KernelInterface::class), $request, KernelInterface::MASTER_REQUEST); - $sessionStrategy = $this->getMockBuilder(\Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface::class)->getMock(); + $sessionStrategy = $this->createMock(SessionAuthenticationStrategyInterface::class); $sessionStrategy->expects($this->once()) ->method('onAuthentication') ->with($request, $this->isInstanceOf(TokenInterface::class)); @@ -233,7 +236,7 @@ public function testMigratesViaSessionStrategy() private function configurePreviousSession(Request $request) { - $session = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\SessionInterface::class)->getMock(); + $session = $this->createMock(SessionInterface::class); $session->expects($this->any()) ->method('getName') ->willReturn('test_session_name'); diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/X509AuthenticationListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/X509AuthenticationListenerTest.php index 52ed2368898a..d48525b4d5f7 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/X509AuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/X509AuthenticationListenerTest.php @@ -13,6 +13,9 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Security\Core\Exception\BadCredentialsException; use Symfony\Component\Security\Http\Firewall\X509AuthenticationListener; class X509AuthenticationListenerTest extends TestCase @@ -32,9 +35,9 @@ public function testGetPreAuthenticatedData($user, $credentials) $request = new Request([], [], [], [], [], $serverVars); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $listener = new X509AuthenticationListener($tokenStorage, $authenticationManager, 'TheProviderKey'); @@ -60,9 +63,9 @@ public function testGetPreAuthenticatedDataNoUser($emailAddress, $credentials) { $request = new Request([], [], [], [], [], ['SSL_CLIENT_S_DN' => $credentials]); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $listener = new X509AuthenticationListener($tokenStorage, $authenticationManager, 'TheProviderKey'); @@ -86,12 +89,12 @@ public static function dataProviderGetPreAuthenticatedDataNoUser() public function testGetPreAuthenticatedDataNoData() { - $this->expectException(\Symfony\Component\Security\Core\Exception\BadCredentialsException::class); + $this->expectException(BadCredentialsException::class); $request = new Request([], [], [], [], [], []); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $listener = new X509AuthenticationListener($tokenStorage, $authenticationManager, 'TheProviderKey'); @@ -109,9 +112,9 @@ public function testGetPreAuthenticatedDataWithDifferentKeys() 'TheUserKey' => 'TheUser', 'TheCredentialsKey' => 'TheCredentials', ]); - $tokenStorage = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); - $authenticationManager = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface::class)->getMock(); + $authenticationManager = $this->createMock(AuthenticationManagerInterface::class); $listener = new X509AuthenticationListener($tokenStorage, $authenticationManager, 'TheProviderKey', 'TheUserKey', 'TheCredentialsKey'); diff --git a/src/Symfony/Component/Security/Http/Tests/FirewallMapTest.php b/src/Symfony/Component/Security/Http/Tests/FirewallMapTest.php index 3eb2607ba6b6..bc3a1a053824 100644 --- a/src/Symfony/Component/Security/Http/Tests/FirewallMapTest.php +++ b/src/Symfony/Component/Security/Http/Tests/FirewallMapTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestMatcher; +use Symfony\Component\Security\Http\Firewall\ExceptionListener; use Symfony\Component\Security\Http\FirewallMap; class FirewallMapTest extends TestCase @@ -23,7 +25,7 @@ public function testGetListeners() $request = new Request(); - $notMatchingMatcher = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestMatcher::class)->getMock(); + $notMatchingMatcher = $this->createMock(RequestMatcher::class); $notMatchingMatcher ->expects($this->once()) ->method('matches') @@ -33,7 +35,7 @@ public function testGetListeners() $map->add($notMatchingMatcher, [function () {}]); - $matchingMatcher = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestMatcher::class)->getMock(); + $matchingMatcher = $this->createMock(RequestMatcher::class); $matchingMatcher ->expects($this->once()) ->method('matches') @@ -41,11 +43,11 @@ public function testGetListeners() ->willReturn(true) ; $theListener = function () {}; - $theException = $this->getMockBuilder(\Symfony\Component\Security\Http\Firewall\ExceptionListener::class)->disableOriginalConstructor()->getMock(); + $theException = $this->createMock(ExceptionListener::class); $map->add($matchingMatcher, [$theListener], $theException); - $tooLateMatcher = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestMatcher::class)->getMock(); + $tooLateMatcher = $this->createMock(RequestMatcher::class); $tooLateMatcher ->expects($this->never()) ->method('matches') @@ -65,7 +67,7 @@ public function testGetListenersWithAnEntryHavingNoRequestMatcher() $request = new Request(); - $notMatchingMatcher = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestMatcher::class)->getMock(); + $notMatchingMatcher = $this->createMock(RequestMatcher::class); $notMatchingMatcher ->expects($this->once()) ->method('matches') @@ -76,11 +78,11 @@ public function testGetListenersWithAnEntryHavingNoRequestMatcher() $map->add($notMatchingMatcher, [function () {}]); $theListener = function () {}; - $theException = $this->getMockBuilder(\Symfony\Component\Security\Http\Firewall\ExceptionListener::class)->disableOriginalConstructor()->getMock(); + $theException = $this->createMock(ExceptionListener::class); $map->add(null, [$theListener], $theException); - $tooLateMatcher = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestMatcher::class)->getMock(); + $tooLateMatcher = $this->createMock(RequestMatcher::class); $tooLateMatcher ->expects($this->never()) ->method('matches') @@ -100,7 +102,7 @@ public function testGetListenersWithNoMatchingEntry() $request = new Request(); - $notMatchingMatcher = $this->getMockBuilder(\Symfony\Component\HttpFoundation\RequestMatcher::class)->getMock(); + $notMatchingMatcher = $this->createMock(RequestMatcher::class); $notMatchingMatcher ->expects($this->once()) ->method('matches') diff --git a/src/Symfony/Component/Security/Http/Tests/FirewallTest.php b/src/Symfony/Component/Security/Http/Tests/FirewallTest.php index 77cb3948e74b..9f14c6de2eb8 100644 --- a/src/Symfony/Component/Security/Http/Tests/FirewallTest.php +++ b/src/Symfony/Component/Security/Http/Tests/FirewallTest.php @@ -24,18 +24,18 @@ class FirewallTest extends TestCase { public function testOnKernelRequestRegistersExceptionListener() { - $dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); + $dispatcher = $this->createMock(EventDispatcherInterface::class); - $listener = $this->getMockBuilder(ExceptionListener::class)->disableOriginalConstructor()->getMock(); + $listener = $this->createMock(ExceptionListener::class); $listener ->expects($this->once()) ->method('register') ->with($this->equalTo($dispatcher)) ; - $request = $this->getMockBuilder(Request::class)->disableOriginalConstructor()->disableOriginalClone()->getMock(); + $request = $this->createMock(Request::class); - $map = $this->getMockBuilder(FirewallMapInterface::class)->getMock(); + $map = $this->createMock(FirewallMapInterface::class); $map ->expects($this->once()) ->method('getListeners') @@ -43,7 +43,7 @@ public function testOnKernelRequestRegistersExceptionListener() ->willReturn([[], $listener, null]) ; - $event = new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $request, HttpKernelInterface::MASTER_REQUEST); + $event = new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST); $firewall = new Firewall($map, $dispatcher); $firewall->onKernelRequest($event); @@ -61,7 +61,7 @@ public function testOnKernelRequestStopsWhenThereIsAResponse() $called[] = 2; }; - $map = $this->getMockBuilder(FirewallMapInterface::class)->getMock(); + $map = $this->createMock(FirewallMapInterface::class); $map ->expects($this->once()) ->method('getListeners') @@ -71,8 +71,8 @@ public function testOnKernelRequestStopsWhenThereIsAResponse() $event = $this->getMockBuilder(RequestEvent::class) ->setMethods(['hasResponse']) ->setConstructorArgs([ - $this->getMockBuilder(HttpKernelInterface::class)->getMock(), - $this->getMockBuilder(Request::class)->disableOriginalConstructor()->disableOriginalClone()->getMock(), + $this->createMock(HttpKernelInterface::class), + $this->createMock(Request::class), HttpKernelInterface::MASTER_REQUEST, ]) ->getMock() @@ -83,7 +83,7 @@ public function testOnKernelRequestStopsWhenThereIsAResponse() ->willReturn(true) ; - $firewall = new Firewall($map, $this->getMockBuilder(EventDispatcherInterface::class)->getMock()); + $firewall = new Firewall($map, $this->createMock(EventDispatcherInterface::class)); $firewall->onKernelRequest($event); $this->assertSame([1], $called); @@ -91,19 +91,19 @@ public function testOnKernelRequestStopsWhenThereIsAResponse() public function testOnKernelRequestWithSubRequest() { - $map = $this->getMockBuilder(FirewallMapInterface::class)->getMock(); + $map = $this->createMock(FirewallMapInterface::class); $map ->expects($this->never()) ->method('getListeners') ; $event = new RequestEvent( - $this->getMockBuilder(HttpKernelInterface::class)->getMock(), - $this->getMockBuilder(Request::class)->getMock(), + $this->createMock(HttpKernelInterface::class), + $this->createMock(Request::class), HttpKernelInterface::SUB_REQUEST ); - $firewall = new Firewall($map, $this->getMockBuilder(EventDispatcherInterface::class)->getMock()); + $firewall = new Firewall($map, $this->createMock(EventDispatcherInterface::class)); $firewall->onKernelRequest($event); $this->assertFalse($event->hasResponse()); @@ -115,9 +115,9 @@ public function testOnKernelRequestWithSubRequest() */ public function testMissingLogoutListener() { - $dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); + $dispatcher = $this->createMock(EventDispatcherInterface::class); - $listener = $this->getMockBuilder(ExceptionListener::class)->disableOriginalConstructor()->getMock(); + $listener = $this->createMock(ExceptionListener::class); $listener ->expects($this->once()) ->method('register') @@ -126,7 +126,7 @@ public function testMissingLogoutListener() $request = new Request(); - $map = $this->getMockBuilder(FirewallMapInterface::class)->getMock(); + $map = $this->createMock(FirewallMapInterface::class); $map ->expects($this->once()) ->method('getListeners') @@ -135,6 +135,6 @@ public function testMissingLogoutListener() ; $firewall = new Firewall($map, $dispatcher); - $firewall->onKernelRequest(new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $request, HttpKernelInterface::MASTER_REQUEST)); + $firewall->onKernelRequest(new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST)); } } diff --git a/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php b/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php index 932f1cfb5586..4d07f0a10002 100644 --- a/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php +++ b/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php @@ -13,9 +13,13 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use Symfony\Component\Routing\Matcher\RequestMatcherInterface; +use Symfony\Component\Routing\Matcher\UrlMatcherInterface; +use Symfony\Component\Routing\RequestContext; use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Http\HttpUtils; @@ -86,7 +90,7 @@ public function testCreateRedirectResponseWithProtocolRelativeTarget() public function testCreateRedirectResponseWithRouteName() { - $utils = new HttpUtils($urlGenerator = $this->getMockBuilder(UrlGeneratorInterface::class)->getMock()); + $utils = new HttpUtils($urlGenerator = $this->createMock(UrlGeneratorInterface::class)); $urlGenerator ->expects($this->any()) @@ -97,7 +101,7 @@ public function testCreateRedirectResponseWithRouteName() $urlGenerator ->expects($this->any()) ->method('getContext') - ->willReturn($this->getMockBuilder(\Symfony\Component\Routing\RequestContext::class)->getMock()) + ->willReturn($this->createMock(RequestContext::class)) ; $response = $utils->createRedirectResponse($this->getRequest(), 'foobar'); @@ -120,7 +124,7 @@ public function testCreateRequestWithPath() public function testCreateRequestWithRouteName() { - $utils = new HttpUtils($urlGenerator = $this->getMockBuilder(UrlGeneratorInterface::class)->getMock()); + $utils = new HttpUtils($urlGenerator = $this->createMock(UrlGeneratorInterface::class)); $urlGenerator ->expects($this->once()) @@ -130,7 +134,7 @@ public function testCreateRequestWithRouteName() $urlGenerator ->expects($this->any()) ->method('getContext') - ->willReturn($this->getMockBuilder(\Symfony\Component\Routing\RequestContext::class)->getMock()) + ->willReturn($this->createMock(RequestContext::class)) ; $subRequest = $utils->createRequest($this->getRequest(), 'foobar'); @@ -140,7 +144,7 @@ public function testCreateRequestWithRouteName() public function testCreateRequestWithAbsoluteUrl() { - $utils = new HttpUtils($this->getMockBuilder(UrlGeneratorInterface::class)->getMock()); + $utils = new HttpUtils($this->createMock(UrlGeneratorInterface::class)); $subRequest = $utils->createRequest($this->getRequest(), 'http://symfony.com/'); $this->assertEquals('/', $subRequest->getPathInfo()); @@ -149,7 +153,7 @@ public function testCreateRequestWithAbsoluteUrl() public function testCreateRequestPassesSessionToTheNewRequest() { $request = $this->getRequest(); - $request->setSession($session = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\SessionInterface::class)->getMock()); + $request->setSession($session = $this->createMock(SessionInterface::class)); $utils = new HttpUtils($this->getUrlGenerator()); $subRequest = $utils->createRequest($request, '/foobar'); @@ -195,7 +199,7 @@ public function testCheckRequestPath() public function testCheckRequestPathWithUrlMatcherAndResourceNotFound() { - $urlMatcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\UrlMatcherInterface::class)->getMock(); + $urlMatcher = $this->createMock(UrlMatcherInterface::class); $urlMatcher ->expects($this->any()) ->method('match') @@ -210,7 +214,7 @@ public function testCheckRequestPathWithUrlMatcherAndResourceNotFound() public function testCheckRequestPathWithUrlMatcherAndMethodNotAllowed() { $request = $this->getRequest(); - $urlMatcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\RequestMatcherInterface::class)->getMock(); + $urlMatcher = $this->createMock(RequestMatcherInterface::class); $urlMatcher ->expects($this->any()) ->method('matchRequest') @@ -224,7 +228,7 @@ public function testCheckRequestPathWithUrlMatcherAndMethodNotAllowed() public function testCheckRequestPathWithUrlMatcherAndResourceFoundByUrl() { - $urlMatcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\UrlMatcherInterface::class)->getMock(); + $urlMatcher = $this->createMock(UrlMatcherInterface::class); $urlMatcher ->expects($this->any()) ->method('match') @@ -239,7 +243,7 @@ public function testCheckRequestPathWithUrlMatcherAndResourceFoundByUrl() public function testCheckRequestPathWithUrlMatcherAndResourceFoundByRequest() { $request = $this->getRequest(); - $urlMatcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\RequestMatcherInterface::class)->getMock(); + $urlMatcher = $this->createMock(RequestMatcherInterface::class); $urlMatcher ->expects($this->any()) ->method('matchRequest') @@ -254,7 +258,7 @@ public function testCheckRequestPathWithUrlMatcherAndResourceFoundByRequest() public function testCheckRequestPathWithUrlMatcherLoadingException() { $this->expectException(\RuntimeException::class); - $urlMatcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\UrlMatcherInterface::class)->getMock(); + $urlMatcher = $this->createMock(UrlMatcherInterface::class); $urlMatcher ->expects($this->any()) ->method('match') @@ -267,7 +271,7 @@ public function testCheckRequestPathWithUrlMatcherLoadingException() public function testCheckPathWithoutRouteParam() { - $urlMatcher = $this->getMockBuilder(\Symfony\Component\Routing\Matcher\UrlMatcherInterface::class)->getMock(); + $urlMatcher = $this->createMock(UrlMatcherInterface::class); $urlMatcher ->expects($this->any()) ->method('match') @@ -313,7 +317,7 @@ public function testUrlGeneratorIsRequiredToGenerateUrl() private function getUrlGenerator($generatedUrl = '/foo/bar') { - $urlGenerator = $this->getMockBuilder(UrlGeneratorInterface::class)->getMock(); + $urlGenerator = $this->createMock(UrlGeneratorInterface::class); $urlGenerator ->expects($this->any()) ->method('generate') diff --git a/src/Symfony/Component/Security/Http/Tests/Logout/CookieClearingLogoutHandlerTest.php b/src/Symfony/Component/Security/Http/Tests/Logout/CookieClearingLogoutHandlerTest.php index cee1d5076a95..88b8288008cb 100644 --- a/src/Symfony/Component/Security/Http/Tests/Logout/CookieClearingLogoutHandlerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Logout/CookieClearingLogoutHandlerTest.php @@ -16,6 +16,7 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ResponseHeaderBag; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Http\Logout\CookieClearingLogoutHandler; class CookieClearingLogoutHandlerTest extends TestCase @@ -24,7 +25,7 @@ public function testLogout() { $request = new Request(); $response = new Response(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $handler = new CookieClearingLogoutHandler(['foo' => ['path' => '/foo', 'domain' => 'foo.foo', 'secure' => true, 'samesite' => Cookie::SAMESITE_STRICT], 'foo2' => ['path' => null, 'domain' => null]]); diff --git a/src/Symfony/Component/Security/Http/Tests/Logout/CsrfTokenClearingLogoutHandlerTest.php b/src/Symfony/Component/Security/Http/Tests/Logout/CsrfTokenClearingLogoutHandlerTest.php index 7e75ce454992..13f2f3350745 100644 --- a/src/Symfony/Component/Security/Http/Tests/Logout/CsrfTokenClearingLogoutHandlerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Logout/CsrfTokenClearingLogoutHandlerTest.php @@ -16,6 +16,7 @@ use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage; use Symfony\Component\Security\Http\Logout\CsrfTokenClearingLogoutHandler; @@ -39,7 +40,7 @@ public function testCsrfTokenCookieWithSameNamespaceIsRemoved() $this->assertSame('bar', $this->session->get('foo/foo')); $this->assertSame('baz', $this->session->get('foo/foobar')); - $this->csrfTokenClearingLogoutHandler->logout(new Request(), new Response(), $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()); + $this->csrfTokenClearingLogoutHandler->logout(new Request(), new Response(), $this->createMock(TokenInterface::class)); $this->assertFalse($this->csrfTokenStorage->hasToken('foo')); $this->assertFalse($this->csrfTokenStorage->hasToken('foobar')); @@ -59,7 +60,7 @@ public function testCsrfTokenCookieWithDifferentNamespaceIsNotRemoved() $this->assertSame('bar', $this->session->get('bar/foo')); $this->assertSame('baz', $this->session->get('bar/foobar')); - $this->csrfTokenClearingLogoutHandler->logout(new Request(), new Response(), $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()); + $this->csrfTokenClearingLogoutHandler->logout(new Request(), new Response(), $this->createMock(TokenInterface::class)); $this->assertTrue($barNamespaceCsrfSessionStorage->hasToken('foo')); $this->assertTrue($barNamespaceCsrfSessionStorage->hasToken('foobar')); diff --git a/src/Symfony/Component/Security/Http/Tests/Logout/DefaultLogoutSuccessHandlerTest.php b/src/Symfony/Component/Security/Http/Tests/Logout/DefaultLogoutSuccessHandlerTest.php index 24e198228fd5..b30592902ea7 100644 --- a/src/Symfony/Component/Security/Http/Tests/Logout/DefaultLogoutSuccessHandlerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Logout/DefaultLogoutSuccessHandlerTest.php @@ -13,16 +13,18 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\RedirectResponse; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Security\Http\HttpUtils; use Symfony\Component\Security\Http\Logout\DefaultLogoutSuccessHandler; class DefaultLogoutSuccessHandlerTest extends TestCase { public function testLogout() { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->getMock(); + $request = $this->createMock(Request::class); $response = new RedirectResponse('/dashboard'); - $httpUtils = $this->getMockBuilder(\Symfony\Component\Security\Http\HttpUtils::class)->getMock(); + $httpUtils = $this->createMock(HttpUtils::class); $httpUtils->expects($this->once()) ->method('createRedirectResponse') ->with($request, '/dashboard') diff --git a/src/Symfony/Component/Security/Http/Tests/Logout/LogoutUrlGeneratorTest.php b/src/Symfony/Component/Security/Http/Tests/Logout/LogoutUrlGeneratorTest.php index 08e2a730bfdc..584170763be9 100644 --- a/src/Symfony/Component/Security/Http/Tests/Logout/LogoutUrlGeneratorTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Logout/LogoutUrlGeneratorTest.php @@ -31,8 +31,8 @@ class LogoutUrlGeneratorTest extends TestCase protected function setUp(): void { - $requestStack = $this->getMockBuilder(RequestStack::class)->getMock(); - $request = $this->getMockBuilder(Request::class)->getMock(); + $requestStack = $this->createMock(RequestStack::class); + $request = $this->createMock(Request::class); $requestStack->method('getCurrentRequest')->willReturn($request); $this->tokenStorage = new TokenStorage(); diff --git a/src/Symfony/Component/Security/Http/Tests/Logout/SessionLogoutHandlerTest.php b/src/Symfony/Component/Security/Http/Tests/Logout/SessionLogoutHandlerTest.php index f8fb31dbea8f..60551abdd756 100644 --- a/src/Symfony/Component/Security/Http/Tests/Logout/SessionLogoutHandlerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Logout/SessionLogoutHandlerTest.php @@ -12,7 +12,10 @@ namespace Symfony\Component\Security\Http\Tests\Logout; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\Session\Session; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Http\Logout\SessionLogoutHandler; class SessionLogoutHandlerTest extends TestCase @@ -21,9 +24,9 @@ public function testLogout() { $handler = new SessionLogoutHandler(); - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->getMock(); + $request = $this->createMock(Request::class); $response = new Response(); - $session = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\Session::class)->disableOriginalConstructor()->getMock(); + $session = $this->createMock(Session::class); $request ->expects($this->once()) @@ -36,6 +39,6 @@ public function testLogout() ->method('invalidate') ; - $handler->logout($request, $response, $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock()); + $handler->logout($request, $response, $this->createMock(TokenInterface::class)); } } diff --git a/src/Symfony/Component/Security/Http/Tests/RememberMe/AbstractRememberMeServicesTest.php b/src/Symfony/Component/Security/Http/Tests/RememberMe/AbstractRememberMeServicesTest.php index 605590803107..39bce812bfa9 100644 --- a/src/Symfony/Component/Security/Http/Tests/RememberMe/AbstractRememberMeServicesTest.php +++ b/src/Symfony/Component/Security/Http/Tests/RememberMe/AbstractRememberMeServicesTest.php @@ -12,8 +12,12 @@ namespace Symfony\Component\Security\Http\Tests\RememberMe; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; +use Symfony\Component\Security\Core\User\UserInterface; +use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Http\RememberMe\AbstractRememberMeServices; use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface; @@ -72,7 +76,7 @@ public function testAutoLogin() $request = new Request(); $request->cookies->set('foo', 'foo'); - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user ->expects($this->once()) ->method('getRoles') @@ -100,10 +104,10 @@ public function testLogout(array $options) $service = $this->getService(null, $options); $request = new Request(); $response = new Response(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $service->logout($request, $response, $token); $cookie = $request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME); - $this->assertInstanceOf(\Symfony\Component\HttpFoundation\Cookie::class, $cookie); + $this->assertInstanceOf(Cookie::class, $cookie); $this->assertTrue($cookie->isCleared()); $this->assertSame($options['name'], $cookie->getName()); $this->assertSame($options['path'], $cookie->getPath()); @@ -135,7 +139,7 @@ public function testLoginSuccessIsNotProcessedWhenTokenDoesNotContainUserInterfa $service = $this->getService(null, ['name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null]); $request = new Request(); $response = new Response(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $token ->expects($this->once()) ->method('getUser') @@ -157,8 +161,8 @@ public function testLoginSuccessIsNotProcessedWhenRememberMeIsNotRequested() $service = $this->getService(null, ['name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo', 'path' => null, 'domain' => null]); $request = new Request(); $response = new Response(); - $account = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $account = $this->createMock(UserInterface::class); + $token = $this->createMock(TokenInterface::class); $token ->expects($this->once()) ->method('getUser') @@ -181,8 +185,8 @@ public function testLoginSuccessWhenRememberMeAlwaysIsTrue() $service = $this->getService(null, ['name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null]); $request = new Request(); $response = new Response(); - $account = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $account = $this->createMock(UserInterface::class); + $token = $this->createMock(TokenInterface::class); $token ->expects($this->once()) ->method('getUser') @@ -208,8 +212,8 @@ public function testLoginSuccessWhenRememberMeParameterWithPathIsPositive($value $request = new Request(); $request->request->set('foo', ['bar' => $value]); $response = new Response(); - $account = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $account = $this->createMock(UserInterface::class); + $token = $this->createMock(TokenInterface::class); $token ->expects($this->once()) ->method('getUser') @@ -235,8 +239,8 @@ public function testLoginSuccessWhenRememberMeParameterIsPositive($value) $request = new Request(); $request->request->set('foo', $value); $response = new Response(); - $account = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $account = $this->createMock(UserInterface::class); + $token = $this->createMock(TokenInterface::class); $token ->expects($this->once()) ->method('getUser') @@ -298,7 +302,7 @@ protected function getService($userProvider = null, $options = [], $logger = nul protected function getProvider() { - $provider = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserProviderInterface::class)->getMock(); + $provider = $this->createMock(UserProviderInterface::class); $provider ->expects($this->any()) ->method('supportsClass') diff --git a/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.php b/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.php index 5b9157f45504..c7bb04341eed 100644 --- a/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.php +++ b/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.php @@ -17,9 +17,14 @@ use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken; +use Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface; +use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\CookieTheftException; use Symfony\Component\Security\Core\Exception\TokenNotFoundException; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; +use Symfony\Component\Security\Core\User\UserInterface; +use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Http\RememberMe\PersistentTokenBasedRememberMeServices; use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface; @@ -62,7 +67,7 @@ public function testAutoLoginThrowsExceptionOnNonExistentToken() $tokenValue = 'foovalue', ])); - $tokenProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface::class)->getMock(); + $tokenProvider = $this->createMock(TokenProviderInterface::class); $tokenProvider ->expects($this->once()) ->method('loadTokenBySeries') @@ -81,7 +86,7 @@ public function testAutoLoginReturnsNullOnNonExistentUser() $request = new Request(); $request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue'])); - $tokenProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface::class)->getMock(); + $tokenProvider = $this->createMock(TokenProviderInterface::class); $tokenProvider ->expects($this->once()) ->method('loadTokenBySeries') @@ -106,7 +111,7 @@ public function testAutoLoginThrowsExceptionOnStolenCookieAndRemovesItFromThePer $request = new Request(); $request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue'])); - $tokenProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface::class)->getMock(); + $tokenProvider = $this->createMock(TokenProviderInterface::class); $service->setTokenProvider($tokenProvider); $tokenProvider @@ -137,7 +142,7 @@ public function testAutoLoginDoesNotAcceptAnExpiredCookie() $request = new Request(); $request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue'])); - $tokenProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface::class)->getMock(); + $tokenProvider = $this->createMock(TokenProviderInterface::class); $tokenProvider ->expects($this->once()) ->method('loadTokenBySeries') @@ -152,7 +157,7 @@ public function testAutoLoginDoesNotAcceptAnExpiredCookie() public function testAutoLogin() { - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user ->expects($this->once()) ->method('getRoles') @@ -171,7 +176,7 @@ public function testAutoLogin() $request = new Request(); $request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue'])); - $tokenProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface::class)->getMock(); + $tokenProvider = $this->createMock(TokenProviderInterface::class); $tokenProvider ->expects($this->once()) ->method('loadTokenBySeries') @@ -182,7 +187,7 @@ public function testAutoLogin() $returnedToken = $service->autoLogin($request); - $this->assertInstanceOf(\Symfony\Component\Security\Core\Authentication\Token\RememberMeToken::class, $returnedToken); + $this->assertInstanceOf(RememberMeToken::class, $returnedToken); $this->assertSame($user, $returnedToken->getUser()); $this->assertEquals('foosecret', $returnedToken->getSecret()); $this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME)); @@ -194,9 +199,9 @@ public function testLogout() $request = new Request(); $request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue'])); $response = new Response(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); - $tokenProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface::class)->getMock(); + $tokenProvider = $this->createMock(TokenProviderInterface::class); $tokenProvider ->expects($this->once()) ->method('deleteTokenBySeries') @@ -220,9 +225,9 @@ public function testLogoutSimplyIgnoresNonSetRequestCookie() $service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null]); $request = new Request(); $response = new Response(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); - $tokenProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface::class)->getMock(); + $tokenProvider = $this->createMock(TokenProviderInterface::class); $tokenProvider ->expects($this->never()) ->method('deleteTokenBySeries') @@ -243,9 +248,9 @@ public function testLogoutSimplyIgnoresInvalidCookie() $request = new Request(); $request->cookies->set('foo', 'somefoovalue'); $response = new Response(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); - $tokenProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface::class)->getMock(); + $tokenProvider = $this->createMock(TokenProviderInterface::class); $tokenProvider ->expects($this->never()) ->method('deleteTokenBySeries') @@ -273,20 +278,20 @@ public function testLoginSuccessSetsCookieWhenLoggedInWithNonRememberMeTokenInte $request = new Request(); $response = new Response(); - $account = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $account = $this->createMock(UserInterface::class); $account ->expects($this->once()) ->method('getUsername') ->willReturn('foo') ; - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $token ->expects($this->any()) ->method('getUser') ->willReturn($account) ; - $tokenProvider = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface::class)->getMock(); + $tokenProvider = $this->createMock(TokenProviderInterface::class); $tokenProvider ->expects($this->once()) ->method('createNewToken') @@ -329,7 +334,7 @@ protected function getService($userProvider = null, $options = [], $logger = nul protected function getProvider() { - $provider = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserProviderInterface::class)->getMock(); + $provider = $this->createMock(UserProviderInterface::class); $provider ->expects($this->any()) ->method('supportsClass') diff --git a/src/Symfony/Component/Security/Http/Tests/RememberMe/ResponseListenerTest.php b/src/Symfony/Component/Security/Http/Tests/RememberMe/ResponseListenerTest.php index fb65baa61251..78dfd57474a5 100644 --- a/src/Symfony/Component/Security/Http/Tests/RememberMe/ResponseListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/RememberMe/ResponseListenerTest.php @@ -15,6 +15,7 @@ use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\HttpKernel\Event\ResponseEvent; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\KernelEvents; @@ -83,7 +84,7 @@ private function getRequest(array $attributes = []) private function getResponse() { $response = new Response(); - $response->headers = $this->getMockBuilder(\Symfony\Component\HttpFoundation\ResponseHeaderBag::class)->getMock(); + $response->headers = $this->createMock(ResponseHeaderBag::class); return $response; } diff --git a/src/Symfony/Component/Security/Http/Tests/RememberMe/TokenBasedRememberMeServicesTest.php b/src/Symfony/Component/Security/Http/Tests/RememberMe/TokenBasedRememberMeServicesTest.php index 5a1330f74700..55cfb678f301 100644 --- a/src/Symfony/Component/Security/Http/Tests/RememberMe/TokenBasedRememberMeServicesTest.php +++ b/src/Symfony/Component/Security/Http/Tests/RememberMe/TokenBasedRememberMeServicesTest.php @@ -16,7 +16,11 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ResponseHeaderBag; +use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; +use Symfony\Component\Security\Core\User\UserInterface; +use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface; use Symfony\Component\Security\Http\RememberMe\TokenBasedRememberMeServices; @@ -64,7 +68,7 @@ public function testAutoLoginDoesNotAcceptCookieWithInvalidHash() $request = new Request(); $request->cookies->set('foo', base64_encode('class:'.base64_encode('foouser').':123456789:fooHash')); - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user ->expects($this->once()) ->method('getPassword') @@ -89,7 +93,7 @@ public function testAutoLoginDoesNotAcceptAnExpiredCookie() $request = new Request(); $request->cookies->set('foo', $this->getCookie('fooclass', 'foouser', time() - 1, 'foopass')); - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user ->expects($this->once()) ->method('getPassword') @@ -114,7 +118,7 @@ public function testAutoLoginDoesNotAcceptAnExpiredCookie() */ public function testAutoLogin($username) { - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $user = $this->createMock(UserInterface::class); $user ->expects($this->once()) ->method('getRoles') @@ -140,7 +144,7 @@ public function testAutoLogin($username) $returnedToken = $service->autoLogin($request); - $this->assertInstanceOf(\Symfony\Component\Security\Core\Authentication\Token\RememberMeToken::class, $returnedToken); + $this->assertInstanceOf(RememberMeToken::class, $returnedToken); $this->assertSame($user, $returnedToken->getUser()); $this->assertEquals('foosecret', $returnedToken->getSecret()); } @@ -158,7 +162,7 @@ public function testLogout() $service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null, 'secure' => true, 'httponly' => false]); $request = new Request(); $response = new Response(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $service->logout($request, $response, $token); @@ -188,7 +192,7 @@ public function testLoginSuccessIgnoresTokensWhichDoNotContainAnUserInterfaceImp $service = $this->getService(null, ['name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null]); $request = new Request(); $response = new Response(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); $token ->expects($this->once()) ->method('getUser') @@ -210,8 +214,8 @@ public function testLoginSuccess() $request = new Request(); $response = new Response(); - $token = $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); - $user = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserInterface::class)->getMock(); + $token = $this->createMock(TokenInterface::class); + $user = $this->createMock(UserInterface::class); $user ->expects($this->once()) ->method('getPassword') @@ -275,7 +279,7 @@ protected function getService($userProvider = null, $options = [], $logger = nul protected function getProvider() { - $provider = $this->getMockBuilder(\Symfony\Component\Security\Core\User\UserProviderInterface::class)->getMock(); + $provider = $this->createMock(UserProviderInterface::class); $provider ->expects($this->any()) ->method('supportsClass') diff --git a/src/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.php b/src/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.php index 71798aa843b5..94ff9228bca2 100644 --- a/src/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.php @@ -12,6 +12,9 @@ namespace Symfony\Component\Security\Http\Tests\Session; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Session\SessionInterface; +use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy; class SessionAuthenticationStrategyTest extends TestCase @@ -38,7 +41,7 @@ public function testUnsupportedStrategy() public function testSessionIsMigrated() { - $session = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\SessionInterface::class)->getMock(); + $session = $this->createMock(SessionInterface::class); $session->expects($this->once())->method('migrate')->with($this->equalTo(true)); $strategy = new SessionAuthenticationStrategy(SessionAuthenticationStrategy::MIGRATE); @@ -47,7 +50,7 @@ public function testSessionIsMigrated() public function testSessionIsInvalidated() { - $session = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Session\SessionInterface::class)->getMock(); + $session = $this->createMock(SessionInterface::class); $session->expects($this->once())->method('invalidate'); $strategy = new SessionAuthenticationStrategy(SessionAuthenticationStrategy::INVALIDATE); @@ -56,7 +59,7 @@ public function testSessionIsInvalidated() private function getRequest($session = null) { - $request = $this->getMockBuilder(\Symfony\Component\HttpFoundation\Request::class)->getMock(); + $request = $this->createMock(Request::class); if (null !== $session) { $request->expects($this->any())->method('getSession')->willReturn($session); @@ -67,6 +70,6 @@ private function getRequest($session = null) private function getToken() { - return $this->getMockBuilder(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class)->getMock(); + return $this->createMock(TokenInterface::class); } } diff --git a/src/Symfony/Component/Security/Http/Tests/Util/TargetPathTraitTest.php b/src/Symfony/Component/Security/Http/Tests/Util/TargetPathTraitTest.php index c97363fdafbb..29f4917072cd 100644 --- a/src/Symfony/Component/Security/Http/Tests/Util/TargetPathTraitTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Util/TargetPathTraitTest.php @@ -12,9 +12,7 @@ public function testSetTargetPath() { $obj = new TestClassWithTargetPathTrait(); - $session = $this->getMockBuilder(SessionInterface::class) - ->getMock(); - + $session = $this->createMock(SessionInterface::class); $session->expects($this->once()) ->method('set') ->with('_security.firewall_name.target_path', '/foo'); @@ -26,9 +24,7 @@ public function testGetTargetPath() { $obj = new TestClassWithTargetPathTrait(); - $session = $this->getMockBuilder(SessionInterface::class) - ->getMock(); - + $session = $this->createMock(SessionInterface::class); $session->expects($this->once()) ->method('get') ->with('_security.cool_firewall.target_path') @@ -45,9 +41,7 @@ public function testRemoveTargetPath() { $obj = new TestClassWithTargetPathTrait(); - $session = $this->getMockBuilder(SessionInterface::class) - ->getMock(); - + $session = $this->createMock(SessionInterface::class); $session->expects($this->once()) ->method('remove') ->with('_security.best_firewall.target_path'); diff --git a/src/Symfony/Component/Serializer/Tests/Annotation/DiscriminatorMapTest.php b/src/Symfony/Component/Serializer/Tests/Annotation/DiscriminatorMapTest.php index 6570bc5804c3..c92cbbacb553 100644 --- a/src/Symfony/Component/Serializer/Tests/Annotation/DiscriminatorMapTest.php +++ b/src/Symfony/Component/Serializer/Tests/Annotation/DiscriminatorMapTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Annotation\DiscriminatorMap; +use Symfony\Component\Serializer\Exception\InvalidArgumentException; /** * @author Samuel Roze @@ -35,25 +36,25 @@ public function testGetTypePropertyAndMapping() public function testExceptionWithoutTypeProperty() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); new DiscriminatorMap(['mapping' => ['foo' => 'FooClass']]); } public function testExceptionWithEmptyTypeProperty() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); new DiscriminatorMap(['typeProperty' => '', 'mapping' => ['foo' => 'FooClass']]); } public function testExceptionWithoutMappingProperty() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); new DiscriminatorMap(['typeProperty' => 'type']); } public function testExceptionWitEmptyMappingProperty() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); new DiscriminatorMap(['typeProperty' => 'type', 'mapping' => []]); } } diff --git a/src/Symfony/Component/Serializer/Tests/Annotation/GroupsTest.php b/src/Symfony/Component/Serializer/Tests/Annotation/GroupsTest.php index 45a755e09026..abae8d550883 100644 --- a/src/Symfony/Component/Serializer/Tests/Annotation/GroupsTest.php +++ b/src/Symfony/Component/Serializer/Tests/Annotation/GroupsTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Annotation\Groups; +use Symfony\Component\Serializer\Exception\InvalidArgumentException; /** * @author Kévin Dunglas @@ -21,19 +22,19 @@ class GroupsTest extends TestCase { public function testEmptyGroupsParameter() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); new Groups(['value' => []]); } public function testNotAnArrayGroupsParameter() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); new Groups(['value' => 12]); } public function testInvalidGroupsParameter() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); new Groups(['value' => ['a', 1, new \stdClass()]]); } diff --git a/src/Symfony/Component/Serializer/Tests/Annotation/MaxDepthTest.php b/src/Symfony/Component/Serializer/Tests/Annotation/MaxDepthTest.php index 9fbe55ce07b5..95c6d2d12a3b 100644 --- a/src/Symfony/Component/Serializer/Tests/Annotation/MaxDepthTest.php +++ b/src/Symfony/Component/Serializer/Tests/Annotation/MaxDepthTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Annotation\MaxDepth; +use Symfony\Component\Serializer\Exception\InvalidArgumentException; /** * @author Kévin Dunglas @@ -21,7 +22,7 @@ class MaxDepthTest extends TestCase { public function testNotSetMaxDepthParameter() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Parameter of annotation "Symfony\Component\Serializer\Annotation\MaxDepth" should be set.'); new MaxDepth([]); } @@ -41,7 +42,7 @@ public function provideInvalidValues() */ public function testNotAnIntMaxDepthParameter($value) { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Parameter of annotation "Symfony\Component\Serializer\Annotation\MaxDepth" must be a positive integer.'); new MaxDepth(['value' => $value]); } diff --git a/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php b/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php index 7881b63f6bf4..8866d6ddb16d 100644 --- a/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php +++ b/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Annotation\SerializedName; +use Symfony\Component\Serializer\Exception\InvalidArgumentException; /** * @author Fabien Bourigault @@ -21,7 +22,7 @@ class SerializedNameTest extends TestCase { public function testNotSetSerializedNameParameter() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Parameter of annotation "Symfony\Component\Serializer\Annotation\SerializedName" should be set.'); new SerializedName([]); } @@ -39,7 +40,7 @@ public function provideInvalidValues() */ public function testNotAStringSerializedNameParameter($value) { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Parameter of annotation "Symfony\Component\Serializer\Annotation\SerializedName" must be a non-empty string.'); new SerializedName(['value' => $value]); } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/ChainDecoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/ChainDecoderTest.php index 7ab648669247..5cac8d99a527 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/ChainDecoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/ChainDecoderTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Encoder\ChainDecoder; +use Symfony\Component\Serializer\Encoder\DecoderInterface; +use Symfony\Component\Serializer\Exception\RuntimeException; class ChainDecoderTest extends TestCase { @@ -26,10 +28,7 @@ class ChainDecoderTest extends TestCase protected function setUp(): void { - $this->decoder1 = $this - ->getMockBuilder(\Symfony\Component\Serializer\Encoder\DecoderInterface::class) - ->getMock(); - + $this->decoder1 = $this->createMock(DecoderInterface::class); $this->decoder1 ->method('supportsDecoding') ->willReturnMap([ @@ -39,10 +38,7 @@ protected function setUp(): void [self::FORMAT_3, ['foo' => 'bar'], true], ]); - $this->decoder2 = $this - ->getMockBuilder(\Symfony\Component\Serializer\Encoder\DecoderInterface::class) - ->getMock(); - + $this->decoder2 = $this->createMock(DecoderInterface::class); $this->decoder2 ->method('supportsDecoding') ->willReturnMap([ @@ -72,7 +68,7 @@ public function testDecode() public function testDecodeUnsupportedFormat() { - $this->expectException(\Symfony\Component\Serializer\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->chainDecoder->decode('string_to_decode', self::FORMAT_3); } } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/ChainEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/ChainEncoderTest.php index ba747933b7cd..e80dc4f1843a 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/ChainEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/ChainEncoderTest.php @@ -15,6 +15,7 @@ use Symfony\Component\Serializer\Encoder\ChainEncoder; use Symfony\Component\Serializer\Encoder\EncoderInterface; use Symfony\Component\Serializer\Encoder\NormalizationAwareInterface; +use Symfony\Component\Serializer\Exception\RuntimeException; class ChainEncoderTest extends TestCase { @@ -28,10 +29,7 @@ class ChainEncoderTest extends TestCase protected function setUp(): void { - $this->encoder1 = $this - ->getMockBuilder(EncoderInterface::class) - ->getMock(); - + $this->encoder1 = $this->createMock(EncoderInterface::class); $this->encoder1 ->method('supportsEncoding') ->willReturnMap([ @@ -41,10 +39,7 @@ protected function setUp(): void [self::FORMAT_3, ['foo' => 'bar'], true], ]); - $this->encoder2 = $this - ->getMockBuilder(EncoderInterface::class) - ->getMock(); - + $this->encoder2 = $this->createMock(EncoderInterface::class); $this->encoder2 ->method('supportsEncoding') ->willReturnMap([ @@ -74,7 +69,7 @@ public function testEncode() public function testEncodeUnsupportedFormat() { - $this->expectException(\Symfony\Component\Serializer\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->chainEncoder->encode(['foo' => 123], self::FORMAT_3); } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/JsonDecodeTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/JsonDecodeTest.php index a51e23e56be4..9fd943211d61 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/JsonDecodeTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/JsonDecodeTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Encoder\JsonDecode; use Symfony\Component\Serializer\Encoder\JsonEncoder; +use Symfony\Component\Serializer\Exception\UnexpectedValueException; class JsonDecodeTest extends TestCase { @@ -60,7 +61,7 @@ public function decodeProvider() */ public function testDecodeWithException($value) { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->decode->decode($value, JsonEncoder::FORMAT); } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncodeTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncodeTest.php index 57b74d4c67f9..141ff43227a4 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncodeTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncodeTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Encoder\JsonEncode; use Symfony\Component\Serializer\Encoder\JsonEncoder; +use Symfony\Component\Serializer\Exception\UnexpectedValueException; class JsonEncodeTest extends TestCase { @@ -53,7 +54,7 @@ public function encodeProvider() public function testEncodeWithError() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->encode->encode("\xB1\x31", JsonEncoder::FORMAT); } } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php index 3dedbd327c02..c1d7d496cce7 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Encoder\JsonEncoder; +use Symfony\Component\Serializer\Exception\UnexpectedValueException; use Symfony\Component\Serializer\Normalizer\CustomNormalizer; use Symfony\Component\Serializer\Serializer; @@ -67,7 +68,7 @@ public function testOptions() public function testEncodeNotUtf8WithoutPartialOnError() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $arr = [ 'utf8' => 'Hello World!', 'notUtf8' => "\xb0\xd0\xb5\xd0", diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php index 0064bcefc8e2..8a65982f5696 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php @@ -15,6 +15,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Encoder\XmlEncoder; use Symfony\Component\Serializer\Exception\NotEncodableValueException; +use Symfony\Component\Serializer\Exception\UnexpectedValueException; use Symfony\Component\Serializer\Normalizer\CustomNormalizer; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\Serializer; @@ -86,7 +87,7 @@ public function testSetRootNodeName() public function testDocTypeIsNotAllowed() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessage('Document types are not allowed.'); $this->encoder->decode('', 'foo'); } @@ -708,19 +709,19 @@ public function testDecodeWithoutItemHash() public function testDecodeInvalidXml() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->encoder->decode('', 'xml'); } public function testPreventsComplexExternalEntities() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->encoder->decode(']>&test;', 'xml'); } public function testDecodeEmptyXml() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessage('Invalid XML data, it can not be empty.'); $this->encoder->decode(' ', 'xml'); } @@ -934,7 +935,7 @@ private function createXmlEncoderWithDateTimeNormalizer(): XmlEncoder */ private function createMockDateTimeNormalizer() { - $mock = $this->getMockBuilder(CustomNormalizer::class)->getMock(); + $mock = $this->createMock(CustomNormalizer::class); $mock ->expects($this->once()) diff --git a/src/Symfony/Component/Serializer/Tests/Mapping/AttributeMetadataTest.php b/src/Symfony/Component/Serializer/Tests/Mapping/AttributeMetadataTest.php index 28f51c080c91..cc941c1a1880 100644 --- a/src/Symfony/Component/Serializer/Tests/Mapping/AttributeMetadataTest.php +++ b/src/Symfony/Component/Serializer/Tests/Mapping/AttributeMetadataTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Mapping\AttributeMetadata; +use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface; /** * @author Kévin Dunglas @@ -22,7 +23,7 @@ class AttributeMetadataTest extends TestCase public function testInterface() { $attributeMetadata = new AttributeMetadata('name'); - $this->assertInstanceOf(\Symfony\Component\Serializer\Mapping\AttributeMetadataInterface::class, $attributeMetadata); + $this->assertInstanceOf(AttributeMetadataInterface::class, $attributeMetadata); } public function testGetName() diff --git a/src/Symfony/Component/Serializer/Tests/Mapping/ClassMetadataTest.php b/src/Symfony/Component/Serializer/Tests/Mapping/ClassMetadataTest.php index 9906959e4c68..25ec203356a0 100644 --- a/src/Symfony/Component/Serializer/Tests/Mapping/ClassMetadataTest.php +++ b/src/Symfony/Component/Serializer/Tests/Mapping/ClassMetadataTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Mapping\AttributeMetadata; use Symfony\Component\Serializer\Mapping\ClassMetadata; +use Symfony\Component\Serializer\Mapping\ClassMetadataInterface; /** * @author Kévin Dunglas @@ -23,7 +24,7 @@ class ClassMetadataTest extends TestCase public function testInterface() { $classMetadata = new ClassMetadata('name'); - $this->assertInstanceOf(\Symfony\Component\Serializer\Mapping\ClassMetadataInterface::class, $classMetadata); + $this->assertInstanceOf(ClassMetadataInterface::class, $classMetadata); } public function testAttributeMetadata() diff --git a/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CacheMetadataFactoryTest.php b/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CacheMetadataFactoryTest.php index cd185853b3b8..74fc1006991d 100644 --- a/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CacheMetadataFactoryTest.php +++ b/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CacheMetadataFactoryTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Cache\Adapter\ArrayAdapter; +use Symfony\Component\Serializer\Exception\InvalidArgumentException; use Symfony\Component\Serializer\Mapping\ClassMetadata; use Symfony\Component\Serializer\Mapping\Factory\CacheClassMetadataFactory; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface; @@ -27,7 +28,7 @@ public function testGetMetadataFor() { $metadata = new ClassMetadata(Dummy::class); - $decorated = $this->getMockBuilder(ClassMetadataFactoryInterface::class)->getMock(); + $decorated = $this->createMock(ClassMetadataFactoryInterface::class); $decorated ->expects($this->once()) ->method('getMetadataFor') @@ -43,7 +44,7 @@ public function testGetMetadataFor() public function testHasMetadataFor() { - $decorated = $this->getMockBuilder(ClassMetadataFactoryInterface::class)->getMock(); + $decorated = $this->createMock(ClassMetadataFactoryInterface::class); $decorated ->expects($this->once()) ->method('hasMetadataFor') @@ -57,8 +58,8 @@ public function testHasMetadataFor() public function testInvalidClassThrowsException() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); - $decorated = $this->getMockBuilder(ClassMetadataFactoryInterface::class)->getMock(); + $this->expectException(InvalidArgumentException::class); + $decorated = $this->createMock(ClassMetadataFactoryInterface::class); $factory = new CacheClassMetadataFactory($decorated, new ArrayAdapter()); $factory->getMetadataFor('Not\Exist'); @@ -70,7 +71,7 @@ public function testAnonymousClass() }; $metadata = new ClassMetadata(\get_class($anonymousObject)); - $decorated = $this->getMockBuilder(ClassMetadataFactoryInterface::class)->getMock(); + $decorated = $this->createMock(ClassMetadataFactoryInterface::class); $decorated ->expects($this->once()) ->method('getMetadataFor') diff --git a/src/Symfony/Component/Serializer/Tests/Mapping/Factory/ClassMetadataFactoryTest.php b/src/Symfony/Component/Serializer/Tests/Mapping/Factory/ClassMetadataFactoryTest.php index 596d235ab970..868c3695bd51 100644 --- a/src/Symfony/Component/Serializer/Tests/Mapping/Factory/ClassMetadataFactoryTest.php +++ b/src/Symfony/Component/Serializer/Tests/Mapping/Factory/ClassMetadataFactoryTest.php @@ -14,6 +14,7 @@ use Doctrine\Common\Annotations\AnnotationReader; use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; +use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface; use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader; use Symfony\Component\Serializer\Mapping\Loader\LoaderChain; use Symfony\Component\Serializer\Tests\Mapping\TestClassMetadataFactory; @@ -26,7 +27,7 @@ class ClassMetadataFactoryTest extends TestCase public function testInterface() { $classMetadata = new ClassMetadataFactory(new LoaderChain([])); - $this->assertInstanceOf(\Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface::class, $classMetadata); + $this->assertInstanceOf(ClassMetadataFactoryInterface::class, $classMetadata); } public function testGetMetadataFor() diff --git a/src/Symfony/Component/Serializer/Tests/Mapping/Loader/AnnotationLoaderTest.php b/src/Symfony/Component/Serializer/Tests/Mapping/Loader/AnnotationLoaderTest.php index 1f5166d8789e..137147316d88 100644 --- a/src/Symfony/Component/Serializer/Tests/Mapping/Loader/AnnotationLoaderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Mapping/Loader/AnnotationLoaderTest.php @@ -17,6 +17,7 @@ use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; use Symfony\Component\Serializer\Mapping\ClassMetadata; use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader; +use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface; use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummy; use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummyFirstChild; use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummySecondChild; @@ -40,7 +41,7 @@ protected function setUp(): void public function testInterface() { - $this->assertInstanceOf(\Symfony\Component\Serializer\Mapping\Loader\LoaderInterface::class, $this->loader); + $this->assertInstanceOf(LoaderInterface::class, $this->loader); } public function testLoadClassMetadataReturnsTrueIfSuccessful() diff --git a/src/Symfony/Component/Serializer/Tests/Mapping/Loader/XmlFileLoaderTest.php b/src/Symfony/Component/Serializer/Tests/Mapping/Loader/XmlFileLoaderTest.php index 1d9fdfdf6d68..a17f31960970 100644 --- a/src/Symfony/Component/Serializer/Tests/Mapping/Loader/XmlFileLoaderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Mapping/Loader/XmlFileLoaderTest.php @@ -15,6 +15,7 @@ use Symfony\Component\Serializer\Mapping\AttributeMetadata; use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; use Symfony\Component\Serializer\Mapping\ClassMetadata; +use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface; use Symfony\Component\Serializer\Mapping\Loader\XmlFileLoader; use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummy; use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummyFirstChild; @@ -43,7 +44,7 @@ protected function setUp(): void public function testInterface() { - $this->assertInstanceOf(\Symfony\Component\Serializer\Mapping\Loader\LoaderInterface::class, $this->loader); + $this->assertInstanceOf(LoaderInterface::class, $this->loader); } public function testLoadClassMetadataReturnsTrueIfSuccessful() diff --git a/src/Symfony/Component/Serializer/Tests/Mapping/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/Serializer/Tests/Mapping/Loader/YamlFileLoaderTest.php index 3dc537a72bcb..130a6f35b250 100644 --- a/src/Symfony/Component/Serializer/Tests/Mapping/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Mapping/Loader/YamlFileLoaderTest.php @@ -12,9 +12,11 @@ namespace Symfony\Component\Serializer\Tests\Mapping\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Serializer\Exception\MappingException; use Symfony\Component\Serializer\Mapping\AttributeMetadata; use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; use Symfony\Component\Serializer\Mapping\ClassMetadata; +use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface; use Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader; use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummy; use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummyFirstChild; @@ -43,7 +45,7 @@ protected function setUp(): void public function testInterface() { - $this->assertInstanceOf(\Symfony\Component\Serializer\Mapping\Loader\LoaderInterface::class, $this->loader); + $this->assertInstanceOf(LoaderInterface::class, $this->loader); } public function testLoadClassMetadataReturnsTrueIfSuccessful() @@ -59,7 +61,7 @@ public function testLoadClassMetadataReturnsFalseWhenEmpty() public function testLoadClassMetadataReturnsThrowsInvalidMapping() { - $this->expectException(\Symfony\Component\Serializer\Exception\MappingException::class); + $this->expectException(MappingException::class); $loader = new YamlFileLoader(__DIR__.'/../../Fixtures/invalid-mapping.yml'); $loader->loadClassMetadata($this->metadata); } diff --git a/src/Symfony/Component/Serializer/Tests/NameConverter/CamelCaseToSnakeCaseNameConverterTest.php b/src/Symfony/Component/Serializer/Tests/NameConverter/CamelCaseToSnakeCaseNameConverterTest.php index 15e36a0df450..d3bf3e12635a 100644 --- a/src/Symfony/Component/Serializer/Tests/NameConverter/CamelCaseToSnakeCaseNameConverterTest.php +++ b/src/Symfony/Component/Serializer/Tests/NameConverter/CamelCaseToSnakeCaseNameConverterTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter; +use Symfony\Component\Serializer\NameConverter\NameConverterInterface; /** * @author Kévin Dunglas @@ -22,7 +23,7 @@ class CamelCaseToSnakeCaseNameConverterTest extends TestCase public function testInterface() { $attributeMetadata = new CamelCaseToSnakeCaseNameConverter(); - $this->assertInstanceOf(\Symfony\Component\Serializer\NameConverter\NameConverterInterface::class, $attributeMetadata); + $this->assertInstanceOf(NameConverterInterface::class, $attributeMetadata); } /** diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractNormalizerTest.php index 9c26dd5bf661..85aacb97431a 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractNormalizerTest.php @@ -8,7 +8,9 @@ use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Mapping\AttributeMetadata; use Symfony\Component\Serializer\Mapping\ClassMetadata; +use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface; +use Symfony\Component\Serializer\Mapping\Loader\LoaderChain; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Normalizer\PropertyNormalizer; @@ -39,8 +41,8 @@ class AbstractNormalizerTest extends TestCase protected function setUp(): void { - $loader = $this->getMockBuilder(\Symfony\Component\Serializer\Mapping\Loader\LoaderChain::class)->setConstructorArgs([[]])->getMock(); - $this->classMetadata = $this->getMockBuilder(\Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory::class)->setConstructorArgs([$loader])->getMock(); + $loader = $this->getMockBuilder(LoaderChain::class)->setConstructorArgs([[]])->getMock(); + $this->classMetadata = $this->getMockBuilder(ClassMetadataFactory::class)->setConstructorArgs([$loader])->getMock(); $this->normalizer = new AbstractNormalizerDummy($this->classMetadata); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php index ccc7be237a98..273a42aac70e 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php @@ -15,7 +15,9 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor; use Symfony\Component\PropertyInfo\Type; +use Symfony\Component\Serializer\Exception\ExtraAttributesException; use Symfony\Component\Serializer\Exception\InvalidArgumentException; +use Symfony\Component\Serializer\Exception\LogicException; use Symfony\Component\Serializer\Exception\NotNormalizableValueException; use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata; use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; @@ -61,7 +63,7 @@ public function testInstantiateObjectDenormalizer() public function testDenormalizeWithExtraAttributes() { - $this->expectException(\Symfony\Component\Serializer\Exception\ExtraAttributesException::class); + $this->expectException(ExtraAttributesException::class); $this->expectExceptionMessage('Extra attributes are not allowed ("fooFoo", "fooBar" are unknown).'); $factory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $normalizer = new AbstractObjectNormalizerDummy($factory); @@ -75,7 +77,7 @@ public function testDenormalizeWithExtraAttributes() public function testDenormalizeWithExtraAttributesAndNoGroupsWithMetadataFactory() { - $this->expectException(\Symfony\Component\Serializer\Exception\ExtraAttributesException::class); + $this->expectException(ExtraAttributesException::class); $this->expectExceptionMessage('Extra attributes are not allowed ("fooFoo", "fooBar" are unknown).'); $normalizer = new AbstractObjectNormalizerWithMetadata(); $normalizer->denormalize( @@ -130,7 +132,7 @@ public function testDenormalizeCollectionDecodedFromXmlWithTwoChildren() private function getDenormalizerForDummyCollection() { - $extractor = $this->getMockBuilder(PhpDocExtractor::class)->getMock(); + $extractor = $this->createMock(PhpDocExtractor::class); $extractor->method('getTypes') ->will($this->onConsecutiveCalls( [new Type('array', false, null, true, new Type('int'), new Type('object', false, DummyChild::class))], @@ -185,7 +187,7 @@ public function testDenormalizeNotSerializableObjectToPopulate() private function getDenormalizerForStringCollection() { - $extractor = $this->getMockBuilder(PhpDocExtractor::class)->getMock(); + $extractor = $this->createMock(PhpDocExtractor::class); $extractor->method('getTypes') ->will($this->onConsecutiveCalls( [new Type('array', false, null, true, new Type('int'), new Type('string'))], @@ -278,7 +280,7 @@ public function getTypeForMappedObject($object): ?string */ public function testExtraAttributesException() { - $this->expectException(\Symfony\Component\Serializer\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('A class metadata factory must be provided in the constructor when setting "allow_extra_attributes" to false.'); $normalizer = new ObjectNormalizer(); diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/ArrayDenormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/ArrayDenormalizerTest.php index 1a83c24bf2bd..ff1f85a4523c 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/ArrayDenormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/ArrayDenormalizerTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer; +use Symfony\Component\Serializer\Serializer; use Symfony\Component\Serializer\SerializerInterface; class ArrayDenormalizerTest extends TestCase @@ -30,7 +31,7 @@ class ArrayDenormalizerTest extends TestCase protected function setUp(): void { - $this->serializer = $this->getMockBuilder(\Symfony\Component\Serializer\Serializer::class)->getMock(); + $this->serializer = $this->createMock(Serializer::class); $this->denormalizer = new ArrayDenormalizer(); $this->denormalizer->setSerializer($this->serializer); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/CustomNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/CustomNormalizerTest.php index 8551370d7acf..e3f13fc1f9dd 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/CustomNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/CustomNormalizerTest.php @@ -13,7 +13,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Normalizer\CustomNormalizer; +use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\Serializer; +use Symfony\Component\Serializer\SerializerAwareInterface; use Symfony\Component\Serializer\Tests\Fixtures\ScalarDummy; class CustomNormalizerTest extends TestCase @@ -31,9 +34,9 @@ protected function setUp(): void public function testInterface() { - $this->assertInstanceOf(\Symfony\Component\Serializer\Normalizer\NormalizerInterface::class, $this->normalizer); - $this->assertInstanceOf(\Symfony\Component\Serializer\Normalizer\DenormalizerInterface::class, $this->normalizer); - $this->assertInstanceOf(\Symfony\Component\Serializer\SerializerAwareInterface::class, $this->normalizer); + $this->assertInstanceOf(NormalizerInterface::class, $this->normalizer); + $this->assertInstanceOf(DenormalizerInterface::class, $this->normalizer); + $this->assertInstanceOf(SerializerAwareInterface::class, $this->normalizer); } public function testSerialize() diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/DataUriNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/DataUriNormalizerTest.php index 1e54f5b37bfa..24c5672bea43 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/DataUriNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/DataUriNormalizerTest.php @@ -13,7 +13,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\File\File; +use Symfony\Component\Serializer\Exception\UnexpectedValueException; use Symfony\Component\Serializer\Normalizer\DataUriNormalizer; +use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; /** * @author Kévin Dunglas @@ -36,8 +39,8 @@ protected function setUp(): void public function testInterface() { - $this->assertInstanceOf(\Symfony\Component\Serializer\Normalizer\NormalizerInterface::class, $this->normalizer); - $this->assertInstanceOf(\Symfony\Component\Serializer\Normalizer\DenormalizerInterface::class, $this->normalizer); + $this->assertInstanceOf(NormalizerInterface::class, $this->normalizer); + $this->assertInstanceOf(DenormalizerInterface::class, $this->normalizer); } public function testSupportNormalization() @@ -113,7 +116,7 @@ public function testDenormalizeHttpFoundationFile() public function testGiveNotAccessToLocalFiles() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessage('The provided "data:" URI is not valid.'); $this->normalizer->denormalize('/etc/shadow', 'SplFileObject'); } @@ -123,7 +126,7 @@ public function testGiveNotAccessToLocalFiles() */ public function testInvalidData($uri) { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->normalizer->denormalize($uri, 'SplFileObject'); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/DateIntervalNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/DateIntervalNormalizerTest.php index 414733592d0c..beb1288e4470 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/DateIntervalNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/DateIntervalNormalizerTest.php @@ -3,6 +3,8 @@ namespace Symfony\Component\Serializer\Tests\Normalizer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Serializer\Exception\InvalidArgumentException; +use Symfony\Component\Serializer\Exception\UnexpectedValueException; use Symfony\Component\Serializer\Normalizer\DateIntervalNormalizer; /** @@ -82,7 +84,7 @@ private function doTestNormalizeUsingFormatPassedInConstructor($format, $output, public function testNormalizeInvalidObjectThrowsException() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The object must be an instance of "\DateInterval".'); $this->normalizer->normalize(new \stdClass()); } @@ -130,26 +132,26 @@ private function doTestDenormalizeUsingFormatPassedInConstructor($format, $input public function testDenormalizeExpectsString() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->normalizer->denormalize(1234, \DateInterval::class); } public function testDenormalizeNonISO8601IntervalStringThrowsException() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessage('Expected a valid ISO 8601 interval string.'); $this->normalizer->denormalize('10 years 2 months 3 days', \DateInterval::class, null); } public function testDenormalizeInvalidDataThrowsException() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->normalizer->denormalize('invalid interval', \DateInterval::class); } public function testDenormalizeFormatMismatchThrowsException() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->normalizer->denormalize('P00Y00M00DT00H00M00S', \DateInterval::class, null, [DateIntervalNormalizer::FORMAT_KEY => 'P%yY%mM%dD']); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php index 6be20c5cac0b..576d5eb03f10 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\Serializer\Tests\Normalizer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Serializer\Exception\InvalidArgumentException; +use Symfony\Component\Serializer\Exception\UnexpectedValueException; use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; /** @@ -181,7 +183,7 @@ public function normalizeUsingTimeZonePassedInContextAndExpectedFormatWithMicros public function testNormalizeInvalidObjectThrowsException() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The object must implement the "\DateTimeInterface".'); $this->normalizer->normalize(new \stdClass()); } @@ -270,27 +272,27 @@ public function denormalizeUsingTimezonePassedInContextProvider() public function testDenormalizeInvalidDataThrowsException() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->normalizer->denormalize('invalid date', \DateTimeInterface::class); } public function testDenormalizeNullThrowsException() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessage('The data is either an empty string or null, you should pass a string that can be parsed with the passed format or a valid DateTime string.'); $this->normalizer->denormalize(null, \DateTimeInterface::class); } public function testDenormalizeEmptyStringThrowsException() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessage('The data is either an empty string or null, you should pass a string that can be parsed with the passed format or a valid DateTime string.'); $this->normalizer->denormalize('', \DateTimeInterface::class); } public function testDenormalizeFormatMismatchThrowsException() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->normalizer->denormalize('2016-01-01T00:00:00+00:00', \DateTimeInterface::class, null, [DateTimeNormalizer::FORMAT_KEY => 'Y-m-d|']); } } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeZoneNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeZoneNormalizerTest.php index 0fdbca0497a7..b32e39d033f9 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeZoneNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeZoneNormalizerTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\Serializer\Tests\Normalizer; use PHPUnit\Framework\TestCase; +use Symfony\Component\Serializer\Exception\InvalidArgumentException; +use Symfony\Component\Serializer\Exception\NotNormalizableValueException; use Symfony\Component\Serializer\Normalizer\DateTimeZoneNormalizer; /** @@ -44,7 +46,7 @@ public function testNormalize() public function testNormalizeBadObjectTypeThrowsException() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->normalizer->normalize(new \stdClass()); } @@ -63,13 +65,13 @@ public function testDenormalize() public function testDenormalizeNullTimeZoneThrowsException() { - $this->expectException(\Symfony\Component\Serializer\Exception\NotNormalizableValueException::class); + $this->expectException(NotNormalizableValueException::class); $this->normalizer->denormalize(null, \DateTimeZone::class, null); } public function testDenormalizeBadTimeZoneThrowsException() { - $this->expectException(\Symfony\Component\Serializer\Exception\NotNormalizableValueException::class); + $this->expectException(NotNormalizableValueException::class); $this->normalizer->denormalize('Jupiter/Europa', \DateTimeZone::class, null); } } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php index 5f464f9a5a50..0a542f4ea53f 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php @@ -17,6 +17,7 @@ use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor; use Symfony\Component\PropertyInfo\PropertyInfoExtractor; use Symfony\Component\Serializer\Exception\CircularReferenceException; +use Symfony\Component\Serializer\Exception\LogicException; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader; use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter; @@ -68,7 +69,7 @@ protected function setUp(): void private function createNormalizer(array $defaultContext = []) { - $this->serializer = $this->getMockBuilder(SerializerNormalizer::class)->getMock(); + $this->serializer = $this->createMock(SerializerNormalizer::class); $this->normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext); $this->normalizer->setSerializer($this->serializer); } @@ -424,9 +425,9 @@ public function testLegacyIgnoredAttributes() public function testUnableToNormalizeObjectAttribute() { - $this->expectException(\Symfony\Component\Serializer\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Cannot normalize attribute "object" because the injected serializer is not a normalizer'); - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer = $this->createMock(SerializerInterface::class); $this->normalizer->setSerializer($serializer); $obj = new GetSetDummy(); diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php index 8e9464d801cb..7731b9c500d6 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use Symfony\Component\Serializer\Exception\CircularReferenceException; +use Symfony\Component\Serializer\Exception\InvalidArgumentException; use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\SerializerInterface; @@ -40,7 +42,7 @@ protected function setUp(): void private function createNormalizer(array $defaultContext = []) { - $this->serializer = $this->getMockBuilder(JsonSerializerNormalizer::class)->getMock(); + $this->serializer = $this->createMock(JsonSerializerNormalizer::class); $this->normalizer = new JsonSerializableNormalizer(null, null, $defaultContext); $this->normalizer->setSerializer($this->serializer); } @@ -78,7 +80,7 @@ public function testLegacyCircularNormalize() private function doTestCircularNormalize(bool $legacy = false) { - $this->expectException(\Symfony\Component\Serializer\Exception\CircularReferenceException::class); + $this->expectException(CircularReferenceException::class); $legacy ? $this->normalizer->setCircularReferenceLimit(1) : $this->createNormalizer([JsonSerializableNormalizer::CIRCULAR_REFERENCE_LIMIT => 1]); $this->serializer @@ -96,7 +98,7 @@ private function doTestCircularNormalize(bool $legacy = false) public function testInvalidDataThrowException() { - $this->expectException(\Symfony\Component\Serializer\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The object must implement "JsonSerializable".'); $this->normalizer->normalize(new \stdClass()); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php index 2153092d01b6..5c8c54d66cdc 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php @@ -17,6 +17,9 @@ use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor; use Symfony\Component\PropertyInfo\PropertyInfoExtractor; use Symfony\Component\Serializer\Exception\CircularReferenceException; +use Symfony\Component\Serializer\Exception\LogicException; +use Symfony\Component\Serializer\Exception\RuntimeException; +use Symfony\Component\Serializer\Exception\UnexpectedValueException; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface; use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader; @@ -81,7 +84,7 @@ protected function setUp(): void private function createNormalizer(array $defaultContext = [], ClassMetadataFactoryInterface $classMetadataFactory = null) { - $this->serializer = $this->getMockBuilder(ObjectSerializerNormalizer::class)->getMock(); + $this->serializer = $this->createMock(ObjectSerializerNormalizer::class); $this->normalizer = new ObjectNormalizer($classMetadataFactory, null, null, null, null, null, $defaultContext); $this->normalizer->setSerializer($this->serializer); } @@ -260,7 +263,7 @@ public function testConstructorWithUnconstructableNullableObjectTypeHintDenormal public function testConstructorWithUnknownObjectTypeHintDenormalize() { - $this->expectException(\Symfony\Component\Serializer\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Could not determine the class of the parameter "unknown".'); $data = [ 'id' => 10, @@ -703,9 +706,9 @@ protected function getDenormalizerForTypeEnforcement(): ObjectNormalizer public function testUnableToNormalizeObjectAttribute() { - $this->expectException(\Symfony\Component\Serializer\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Cannot normalize attribute "object" because the injected serializer is not a normalizer'); - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer = $this->createMock(SerializerInterface::class); $this->normalizer->setSerializer($serializer); $obj = new ObjectDummy(); @@ -767,7 +770,7 @@ protected function isCircularReference($object, &$context) public function testThrowUnexpectedValueException() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->normalizer->denormalize(['foo' => 'bar'], ObjectTypeHinted::class); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php index 1a471b78afa4..a2aefb4eda1d 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php @@ -18,6 +18,7 @@ use Symfony\Component\PropertyInfo\PropertyInfoExtractor; use Symfony\Component\Serializer\Exception\CircularReferenceException; use Symfony\Component\Serializer\Exception\InvalidArgumentException; +use Symfony\Component\Serializer\Exception\LogicException; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader; use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter; @@ -71,7 +72,7 @@ protected function setUp(): void private function createNormalizer(array $defaultContext = []) { - $this->serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $this->serializer = $this->createMock(SerializerInterface::class); $this->normalizer = new PropertyNormalizer(null, null, null, null, null, $defaultContext); $this->normalizer->setSerializer($this->serializer); } @@ -395,9 +396,9 @@ public function testDenormalizeShouldIgnoreStaticProperty() public function testUnableToNormalizeObjectAttribute() { - $this->expectException(\Symfony\Component\Serializer\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Cannot normalize attribute "bar" because the injected serializer is not a normalizer'); - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer = $this->createMock(SerializerInterface::class); $this->normalizer->setSerializer($serializer); $obj = new PropertyDummy(); diff --git a/src/Symfony/Component/Serializer/Tests/SerializerTest.php b/src/Symfony/Component/Serializer/Tests/SerializerTest.php index 8179b2b2eb13..e5a8acbf0354 100644 --- a/src/Symfony/Component/Serializer/Tests/SerializerTest.php +++ b/src/Symfony/Component/Serializer/Tests/SerializerTest.php @@ -15,9 +15,14 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor; use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor; +use Symfony\Component\Serializer\Encoder\DecoderInterface; +use Symfony\Component\Serializer\Encoder\EncoderInterface; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Exception\InvalidArgumentException; +use Symfony\Component\Serializer\Exception\LogicException; use Symfony\Component\Serializer\Exception\NotNormalizableValueException; +use Symfony\Component\Serializer\Exception\RuntimeException; +use Symfony\Component\Serializer\Exception\UnexpectedValueException; use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata; use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; use Symfony\Component\Serializer\Mapping\ClassMetadata; @@ -36,6 +41,7 @@ use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Normalizer\PropertyNormalizer; use Symfony\Component\Serializer\Serializer; +use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummy; use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummyFirstChild; use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummySecondChild; @@ -54,11 +60,11 @@ public function testInterface() { $serializer = new Serializer(); - $this->assertInstanceOf(\Symfony\Component\Serializer\SerializerInterface::class, $serializer); + $this->assertInstanceOf(SerializerInterface::class, $serializer); $this->assertInstanceOf(NormalizerInterface::class, $serializer); $this->assertInstanceOf(DenormalizerInterface::class, $serializer); - $this->assertInstanceOf(\Symfony\Component\Serializer\Encoder\EncoderInterface::class, $serializer); - $this->assertInstanceOf(\Symfony\Component\Serializer\Encoder\DecoderInterface::class, $serializer); + $this->assertInstanceOf(EncoderInterface::class, $serializer); + $this->assertInstanceOf(DecoderInterface::class, $serializer); } /** @@ -81,8 +87,8 @@ public function testDeprecationErrorOnInvalidEncoder() public function testNormalizeNoMatch() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); - $serializer = new Serializer([$this->getMockBuilder(CustomNormalizer::class)->getMock()]); + $this->expectException(UnexpectedValueException::class); + $serializer = new Serializer([$this->createMock(CustomNormalizer::class)]); $serializer->normalize(new \stdClass(), 'xml'); } @@ -102,21 +108,21 @@ public function testNormalizeGivesPriorityToInterfaceOverTraversable() public function testNormalizeOnDenormalizer() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([new TestDenormalizer()], []); $this->assertTrue($serializer->normalize(new \stdClass(), 'json')); } public function testDenormalizeNoMatch() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); - $serializer = new Serializer([$this->getMockBuilder(CustomNormalizer::class)->getMock()]); + $this->expectException(UnexpectedValueException::class); + $serializer = new Serializer([$this->createMock(CustomNormalizer::class)]); $serializer->denormalize('foo', 'stdClass'); } public function testDenormalizeOnNormalizer() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([new TestNormalizer()], []); $data = ['title' => 'foo', 'numbers' => [5, 3]]; $this->assertTrue($serializer->denormalize(json_encode($data), 'stdClass', 'json')); @@ -133,14 +139,14 @@ public function testCustomNormalizerCanNormalizeCollectionsAndScalar() public function testNormalizeWithSupportOnData() { - $normalizer1 = $this->getMockBuilder(NormalizerInterface::class)->getMock(); + $normalizer1 = $this->createMock(NormalizerInterface::class); $normalizer1->method('supportsNormalization') ->willReturnCallback(function ($data, $format) { return isset($data->test); }); $normalizer1->method('normalize')->willReturn('test1'); - $normalizer2 = $this->getMockBuilder(NormalizerInterface::class)->getMock(); + $normalizer2 = $this->createMock(NormalizerInterface::class); $normalizer2->method('supportsNormalization') ->willReturn(true); $normalizer2->method('normalize')->willReturn('test2'); @@ -156,14 +162,14 @@ public function testNormalizeWithSupportOnData() public function testDenormalizeWithSupportOnData() { - $denormalizer1 = $this->getMockBuilder(DenormalizerInterface::class)->getMock(); + $denormalizer1 = $this->createMock(DenormalizerInterface::class); $denormalizer1->method('supportsDenormalization') ->willReturnCallback(function ($data, $type, $format) { return isset($data['test1']); }); $denormalizer1->method('denormalize')->willReturn('test1'); - $denormalizer2 = $this->getMockBuilder(DenormalizerInterface::class)->getMock(); + $denormalizer2 = $this->createMock(DenormalizerInterface::class); $denormalizer2->method('supportsDenormalization') ->willReturn(true); $denormalizer2->method('denormalize')->willReturn('test2'); @@ -213,7 +219,7 @@ public function testSerializeEmpty() public function testSerializeNoEncoder() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([], []); $data = ['title' => 'foo', 'numbers' => [5, 3]]; $serializer->serialize($data, 'json'); @@ -221,7 +227,7 @@ public function testSerializeNoEncoder() public function testSerializeNoNormalizer() { - $this->expectException(\Symfony\Component\Serializer\Exception\LogicException::class); + $this->expectException(LogicException::class); $serializer = new Serializer([], ['json' => new JsonEncoder()]); $data = ['title' => 'foo', 'numbers' => [5, 3]]; $serializer->serialize(Model::fromArray($data), 'json'); @@ -247,7 +253,7 @@ public function testDeserializeUseCache() public function testDeserializeNoNormalizer() { - $this->expectException(\Symfony\Component\Serializer\Exception\LogicException::class); + $this->expectException(LogicException::class); $serializer = new Serializer([], ['json' => new JsonEncoder()]); $data = ['title' => 'foo', 'numbers' => [5, 3]]; $serializer->deserialize(json_encode($data), Model::class, 'json'); @@ -255,7 +261,7 @@ public function testDeserializeNoNormalizer() public function testDeserializeWrongNormalizer() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([new CustomNormalizer()], ['json' => new JsonEncoder()]); $data = ['title' => 'foo', 'numbers' => [5, 3]]; $serializer->deserialize(json_encode($data), Model::class, 'json'); @@ -263,7 +269,7 @@ public function testDeserializeWrongNormalizer() public function testDeserializeNoEncoder() { - $this->expectException(\Symfony\Component\Serializer\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([], []); $data = ['title' => 'foo', 'numbers' => [5, 3]]; $serializer->deserialize(json_encode($data), Model::class, 'json'); @@ -353,7 +359,7 @@ public function testDeserializeArray() public function testNormalizerAware() { - $normalizerAware = $this->getMockBuilder(NormalizerAwareNormalizer::class)->getMock(); + $normalizerAware = $this->createMock(NormalizerAwareNormalizer::class); $normalizerAware->expects($this->once()) ->method('setNormalizer') ->with($this->isInstanceOf(NormalizerInterface::class)); @@ -363,7 +369,7 @@ public function testNormalizerAware() public function testDenormalizerAware() { - $denormalizerAware = $this->getMockBuilder(DenormalizerAwareDenormalizer::class)->getMock(); + $denormalizerAware = $this->createMock(DenormalizerAwareDenormalizer::class); $denormalizerAware->expects($this->once()) ->method('setDenormalizer') ->with($this->isInstanceOf(DenormalizerInterface::class)); @@ -471,14 +477,14 @@ public function testDeserializeAndSerializeNestedInterfacedObjectsWithTheClassMe public function testExceptionWhenTypeIsNotKnownInDiscriminator() { - $this->expectException(\Symfony\Component\Serializer\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The type "second" has no mapped class for the abstract object "Symfony\Component\Serializer\Tests\Fixtures\DummyMessageInterface"'); $this->serializerWithClassDiscriminator()->deserialize('{"type":"second","one":1}', DummyMessageInterface::class, 'json'); } public function testExceptionWhenTypeIsNotInTheBodyToDeserialiaze() { - $this->expectException(\Symfony\Component\Serializer\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Type property "type" not found for the abstract object "Symfony\Component\Serializer\Tests\Fixtures\DummyMessageInterface"'); $this->serializerWithClassDiscriminator()->deserialize('{"one":1}', DummyMessageInterface::class, 'json'); } diff --git a/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php b/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php index a5bcb5d72476..75d3bb5d5b0f 100644 --- a/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php +++ b/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php @@ -12,7 +12,9 @@ namespace Symfony\Component\Stopwatch\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Stopwatch\Section; use Symfony\Component\Stopwatch\Stopwatch; +use Symfony\Component\Stopwatch\StopwatchEvent; /** * StopwatchTest. @@ -30,7 +32,7 @@ public function testStart() $stopwatch = new Stopwatch(); $event = $stopwatch->start('foo', 'cat'); - $this->assertInstanceOf(\Symfony\Component\Stopwatch\StopwatchEvent::class, $event); + $this->assertInstanceOf(StopwatchEvent::class, $event); $this->assertEquals('cat', $event->getCategory()); $this->assertSame($event, $stopwatch->getEvent('foo')); } @@ -66,10 +68,10 @@ public function testIsNotStartedEvent() $sections->setAccessible(true); $section = $sections->getValue($stopwatch); - $events = new \ReflectionProperty(\Symfony\Component\Stopwatch\Section::class, 'events'); + $events = new \ReflectionProperty(Section::class, 'events'); $events->setAccessible(true); - $stopwatchMockEvent = $this->getMockBuilder(\Symfony\Component\Stopwatch\StopwatchEvent::class) + $stopwatchMockEvent = $this->getMockBuilder(StopwatchEvent::class) ->setConstructorArgs([microtime(true) * 1000]) ->getMock() ; @@ -86,7 +88,7 @@ public function testStop() usleep(200000); $event = $stopwatch->stop('foo'); - $this->assertInstanceOf(\Symfony\Component\Stopwatch\StopwatchEvent::class, $event); + $this->assertInstanceOf(StopwatchEvent::class, $event); $this->assertEqualsWithDelta(200, $event->getDuration(), self::DELTA); } diff --git a/src/Symfony/Component/Templating/Tests/DelegatingEngineTest.php b/src/Symfony/Component/Templating/Tests/DelegatingEngineTest.php index c590d8557d3a..c3544f9156bd 100644 --- a/src/Symfony/Component/Templating/Tests/DelegatingEngineTest.php +++ b/src/Symfony/Component/Templating/Tests/DelegatingEngineTest.php @@ -121,7 +121,7 @@ public function testGetInvalidEngine() private function getEngineMock($template, $supports) { - $engine = $this->getMockBuilder(EngineInterface::class)->getMock(); + $engine = $this->createMock(EngineInterface::class); $engine->expects($this->once()) ->method('supports') @@ -133,7 +133,7 @@ private function getEngineMock($template, $supports) private function getStreamingEngineMock($template, $supports) { - $engine = $this->getMockForAbstractClass(\Symfony\Component\Templating\Tests\MyStreamingEngine::class); + $engine = $this->getMockForAbstractClass(MyStreamingEngine::class); $engine->expects($this->once()) ->method('supports') diff --git a/src/Symfony/Component/Templating/Tests/Loader/CacheLoaderTest.php b/src/Symfony/Component/Templating/Tests/Loader/CacheLoaderTest.php index d15b9549b0fc..21478202c8a3 100644 --- a/src/Symfony/Component/Templating/Tests/Loader/CacheLoaderTest.php +++ b/src/Symfony/Component/Templating/Tests/Loader/CacheLoaderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Templating\Tests\Loader; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; use Symfony\Component\Templating\Loader\CacheLoader; use Symfony\Component\Templating\Loader\Loader; use Symfony\Component\Templating\Storage\StringStorage; @@ -35,7 +36,7 @@ public function testLoad() $loader = new ProjectTemplateLoader($varLoader = new ProjectTemplateLoaderVar(), $dir); $this->assertFalse($loader->load(new TemplateReference('foo', 'php')), '->load() returns false if the embed loader is not able to load the template'); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $logger ->expects($this->once()) ->method('debug') @@ -43,7 +44,7 @@ public function testLoad() $loader->setLogger($logger); $loader->load(new TemplateReference('index')); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $logger ->expects($this->once()) ->method('debug') diff --git a/src/Symfony/Component/Templating/Tests/Loader/FilesystemLoaderTest.php b/src/Symfony/Component/Templating/Tests/Loader/FilesystemLoaderTest.php index bb63c12fb2ca..998d9e522834 100644 --- a/src/Symfony/Component/Templating/Tests/Loader/FilesystemLoaderTest.php +++ b/src/Symfony/Component/Templating/Tests/Loader/FilesystemLoaderTest.php @@ -12,7 +12,9 @@ namespace Symfony\Component\Templating\Tests\Loader; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; use Symfony\Component\Templating\Loader\FilesystemLoader; +use Symfony\Component\Templating\Storage\FileStorage; use Symfony\Component\Templating\TemplateReference; class FilesystemLoaderTest extends TestCase @@ -49,16 +51,16 @@ public function testLoad() $path = self::$fixturesPath.'/templates'; $loader = new ProjectTemplateLoader2($pathPattern); $storage = $loader->load(new TemplateReference($path.'/foo.php', 'php')); - $this->assertInstanceOf(\Symfony\Component\Templating\Storage\FileStorage::class, $storage, '->load() returns a FileStorage if you pass an absolute path'); + $this->assertInstanceOf(FileStorage::class, $storage, '->load() returns a FileStorage if you pass an absolute path'); $this->assertEquals($path.'/foo.php', (string) $storage, '->load() returns a FileStorage pointing to the passed absolute path'); $this->assertFalse($loader->load(new TemplateReference('bar', 'php')), '->load() returns false if the template is not found'); $storage = $loader->load(new TemplateReference('foo.php', 'php')); - $this->assertInstanceOf(\Symfony\Component\Templating\Storage\FileStorage::class, $storage, '->load() returns a FileStorage if you pass a relative template that exists'); + $this->assertInstanceOf(FileStorage::class, $storage, '->load() returns a FileStorage if you pass a relative template that exists'); $this->assertEquals($path.'/foo.php', (string) $storage, '->load() returns a FileStorage pointing to the absolute path of the template'); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $logger->expects($this->exactly(2))->method('debug'); $loader = new ProjectTemplateLoader2($pathPattern); diff --git a/src/Symfony/Component/Templating/Tests/Loader/LoaderTest.php b/src/Symfony/Component/Templating/Tests/Loader/LoaderTest.php index d31dba872543..327e36bf9d7c 100644 --- a/src/Symfony/Component/Templating/Tests/Loader/LoaderTest.php +++ b/src/Symfony/Component/Templating/Tests/Loader/LoaderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Templating\Tests\Loader; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; use Symfony\Component\Templating\Loader\Loader; use Symfony\Component\Templating\TemplateReferenceInterface; @@ -20,7 +21,7 @@ class LoaderTest extends TestCase public function testGetSetLogger() { $loader = new ProjectTemplateLoader4(); - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $loader->setLogger($logger); $this->assertSame($logger, $loader->getLogger(), '->setLogger() sets the logger instance'); } diff --git a/src/Symfony/Component/Templating/Tests/Storage/FileStorageTest.php b/src/Symfony/Component/Templating/Tests/Storage/FileStorageTest.php index 2a0e73c19520..043967e3a439 100644 --- a/src/Symfony/Component/Templating/Tests/Storage/FileStorageTest.php +++ b/src/Symfony/Component/Templating/Tests/Storage/FileStorageTest.php @@ -13,13 +13,14 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Templating\Storage\FileStorage; +use Symfony\Component\Templating\Storage\Storage; class FileStorageTest extends TestCase { public function testGetContent() { $storage = new FileStorage('foo'); - $this->assertInstanceOf(\Symfony\Component\Templating\Storage\Storage::class, $storage, 'FileStorage is an instance of Storage'); + $this->assertInstanceOf(Storage::class, $storage, 'FileStorage is an instance of Storage'); $storage = new FileStorage(__DIR__.'/../Fixtures/templates/foo.php'); $this->assertEquals(''."\n", $storage->getContent(), '->getContent() returns the content of the template'); } diff --git a/src/Symfony/Component/Templating/Tests/Storage/StringStorageTest.php b/src/Symfony/Component/Templating/Tests/Storage/StringStorageTest.php index 7b32542e1840..d86d65a2aa52 100644 --- a/src/Symfony/Component/Templating/Tests/Storage/StringStorageTest.php +++ b/src/Symfony/Component/Templating/Tests/Storage/StringStorageTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Templating\Tests\Storage; use PHPUnit\Framework\TestCase; +use Symfony\Component\Templating\Storage\Storage; use Symfony\Component\Templating\Storage\StringStorage; class StringStorageTest extends TestCase @@ -19,7 +20,7 @@ class StringStorageTest extends TestCase public function testGetContent() { $storage = new StringStorage('foo'); - $this->assertInstanceOf(\Symfony\Component\Templating\Storage\Storage::class, $storage, 'StringStorage is an instance of Storage'); + $this->assertInstanceOf(Storage::class, $storage, 'StringStorage is an instance of Storage'); $storage = new StringStorage('foo'); $this->assertEquals('foo', $storage->getContent(), '->getContent() returns the content of the template'); } diff --git a/src/Symfony/Component/Translation/Tests/DataCollector/TranslationDataCollectorTest.php b/src/Symfony/Component/Translation/Tests/DataCollector/TranslationDataCollectorTest.php index e1c5f67f0ace..39e74fac96d9 100644 --- a/src/Symfony/Component/Translation/Tests/DataCollector/TranslationDataCollectorTest.php +++ b/src/Symfony/Component/Translation/Tests/DataCollector/TranslationDataCollectorTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Translation\Tests\DataCollector; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpKernel\DataCollector\DataCollector; use Symfony\Component\Translation\DataCollector\TranslationDataCollector; use Symfony\Component\Translation\DataCollectorTranslator; @@ -19,7 +20,7 @@ class TranslationDataCollectorTest extends TestCase { protected function setUp(): void { - if (!class_exists(\Symfony\Component\HttpKernel\DataCollector\DataCollector::class)) { + if (!class_exists(DataCollector::class)) { $this->markTestSkipped('The "DataCollector" is not available'); } } diff --git a/src/Symfony/Component/Translation/Tests/DependencyInjection/TranslationExtractorPassTest.php b/src/Symfony/Component/Translation/Tests/DependencyInjection/TranslationExtractorPassTest.php index 6364b9bcafa5..bcb2ccd45402 100644 --- a/src/Symfony/Component/Translation/Tests/DependencyInjection/TranslationExtractorPassTest.php +++ b/src/Symfony/Component/Translation/Tests/DependencyInjection/TranslationExtractorPassTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\Translation\DependencyInjection\TranslationExtractorPass; @@ -48,7 +49,7 @@ public function testProcessNoDefinitionFound() public function testProcessMissingAlias() { - $this->expectException(\Symfony\Component\DependencyInjection\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The alias for the tag "translation.extractor" of service "foo.id" must be set.'); $container = new ContainerBuilder(); $container->register('translation.extractor'); diff --git a/src/Symfony/Component/Translation/Tests/IntervalTest.php b/src/Symfony/Component/Translation/Tests/IntervalTest.php index 61b88dbb0236..1e1cbf427a8f 100644 --- a/src/Symfony/Component/Translation/Tests/IntervalTest.php +++ b/src/Symfony/Component/Translation/Tests/IntervalTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Translation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Translation\Exception\InvalidArgumentException; use Symfony\Component\Translation\Interval; /** @@ -29,7 +30,7 @@ public function testTest($expected, $number, $interval) public function testTestException() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); Interval::test(1, 'foobar'); } diff --git a/src/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.php index 44cba5f340af..062ea538ece0 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; use Symfony\Component\Translation\Loader\CsvFileLoader; class CsvFileLoaderTest extends TestCase @@ -41,7 +43,7 @@ public function testLoadDoesNothingIfEmpty() public function testLoadNonExistingResource() { - $this->expectException(\Symfony\Component\Translation\Exception\NotFoundResourceException::class); + $this->expectException(NotFoundResourceException::class); $loader = new CsvFileLoader(); $resource = __DIR__.'/../fixtures/not-exists.csv'; $loader->load($resource, 'en', 'domain1'); @@ -49,7 +51,7 @@ public function testLoadNonExistingResource() public function testLoadNonLocalResource() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $loader = new CsvFileLoader(); $resource = 'http://example.com/resources.csv'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.php index fe107210d567..0f7ffa6fdc85 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\Translation\Tests\Loader; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; use Symfony\Component\Translation\Loader\IcuDatFileLoader; /** @@ -21,7 +23,7 @@ class IcuDatFileLoaderTest extends LocalizedTestCase { public function testLoadInvalidResource() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $loader = new IcuDatFileLoader(); $loader->load(__DIR__.'/../fixtures/resourcebundle/corrupted/resources', 'es', 'domain2'); } @@ -53,7 +55,7 @@ public function testDatFrenchLoad() public function testLoadNonExistingResource() { - $this->expectException(\Symfony\Component\Translation\Exception\NotFoundResourceException::class); + $this->expectException(NotFoundResourceException::class); $loader = new IcuDatFileLoader(); $loader->load(__DIR__.'/../fixtures/non-existing.txt', 'en', 'domain1'); } diff --git a/src/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.php index c334652232d5..1388f8a91e6e 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\Translation\Tests\Loader; use Symfony\Component\Config\Resource\DirectoryResource; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; use Symfony\Component\Translation\Loader\IcuResFileLoader; /** @@ -33,14 +35,14 @@ public function testLoad() public function testLoadNonExistingResource() { - $this->expectException(\Symfony\Component\Translation\Exception\NotFoundResourceException::class); + $this->expectException(NotFoundResourceException::class); $loader = new IcuResFileLoader(); $loader->load(__DIR__.'/../fixtures/non-existing.txt', 'en', 'domain1'); } public function testLoadInvalidResource() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $loader = new IcuResFileLoader(); $loader->load(__DIR__.'/../fixtures/resourcebundle/corrupted', 'en', 'domain1'); } diff --git a/src/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.php index 3330e7e37250..9e2027c41e10 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Translation\Exception\NotFoundResourceException; use Symfony\Component\Translation\Loader\IniFileLoader; class IniFileLoaderTest extends TestCase @@ -41,7 +42,7 @@ public function testLoadDoesNothingIfEmpty() public function testLoadNonExistingResource() { - $this->expectException(\Symfony\Component\Translation\Exception\NotFoundResourceException::class); + $this->expectException(NotFoundResourceException::class); $loader = new IniFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.ini'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.php index c3ef1f76282f..6dfaec8d9dec 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; use Symfony\Component\Translation\Loader\JsonFileLoader; class JsonFileLoaderTest extends TestCase @@ -41,7 +43,7 @@ public function testLoadDoesNothingIfEmpty() public function testLoadNonExistingResource() { - $this->expectException(\Symfony\Component\Translation\Exception\NotFoundResourceException::class); + $this->expectException(NotFoundResourceException::class); $loader = new JsonFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.json'; $loader->load($resource, 'en', 'domain1'); @@ -49,7 +51,7 @@ public function testLoadNonExistingResource() public function testParseException() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $this->expectExceptionMessage('Error parsing JSON: Syntax error, malformed JSON'); $loader = new JsonFileLoader(); $resource = __DIR__.'/../fixtures/malformed.json'; diff --git a/src/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.php index 8da81ba8c719..637fb1c7b78d 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; use Symfony\Component\Translation\Loader\MoFileLoader; class MoFileLoaderTest extends TestCase @@ -44,7 +46,7 @@ public function testLoadPlurals() public function testLoadNonExistingResource() { - $this->expectException(\Symfony\Component\Translation\Exception\NotFoundResourceException::class); + $this->expectException(NotFoundResourceException::class); $loader = new MoFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.mo'; $loader->load($resource, 'en', 'domain1'); @@ -52,7 +54,7 @@ public function testLoadNonExistingResource() public function testLoadInvalidResource() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $loader = new MoFileLoader(); $resource = __DIR__.'/../fixtures/empty.mo'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.php index 1b2c9fac0695..ec6ad37b2fbd 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; use Symfony\Component\Translation\Loader\PhpFileLoader; class PhpFileLoaderTest extends TestCase @@ -30,7 +32,7 @@ public function testLoad() public function testLoadNonExistingResource() { - $this->expectException(\Symfony\Component\Translation\Exception\NotFoundResourceException::class); + $this->expectException(NotFoundResourceException::class); $loader = new PhpFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.php'; $loader->load($resource, 'en', 'domain1'); @@ -38,7 +40,7 @@ public function testLoadNonExistingResource() public function testLoadThrowsAnExceptionIfFileNotLocal() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $loader = new PhpFileLoader(); $resource = 'http://example.com/resources.php'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.php index 04c084eac52b..c346a4be4fab 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Translation\Exception\NotFoundResourceException; use Symfony\Component\Translation\Loader\PoFileLoader; class PoFileLoaderTest extends TestCase @@ -55,7 +56,7 @@ public function testLoadDoesNothingIfEmpty() public function testLoadNonExistingResource() { - $this->expectException(\Symfony\Component\Translation\Exception\NotFoundResourceException::class); + $this->expectException(NotFoundResourceException::class); $loader = new PoFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.po'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.php index 0d2817b39c23..0ab69414eb78 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; use Symfony\Component\Translation\Loader\QtFileLoader; class QtFileLoaderTest extends TestCase @@ -34,7 +36,7 @@ public function testLoad() public function testLoadNonExistingResource() { - $this->expectException(\Symfony\Component\Translation\Exception\NotFoundResourceException::class); + $this->expectException(NotFoundResourceException::class); $loader = new QtFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.ts'; $loader->load($resource, 'en', 'domain1'); @@ -42,7 +44,7 @@ public function testLoadNonExistingResource() public function testLoadNonLocalResource() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $loader = new QtFileLoader(); $resource = 'http://domain1.com/resources.ts'; $loader->load($resource, 'en', 'domain1'); @@ -50,7 +52,7 @@ public function testLoadNonLocalResource() public function testLoadInvalidResource() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $loader = new QtFileLoader(); $resource = __DIR__.'/../fixtures/invalid-xml-resources.xlf'; $loader->load($resource, 'en', 'domain1'); @@ -61,7 +63,7 @@ public function testLoadEmptyResource() $loader = new QtFileLoader(); $resource = __DIR__.'/../fixtures/empty.xlf'; - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $this->expectExceptionMessage(sprintf('Unable to load "%s".', $resource)); $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php index 4592bc872a66..164082982ce9 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; use Symfony\Component\Translation\Loader\XliffFileLoader; class XliffFileLoaderTest extends TestCase @@ -112,21 +114,21 @@ public function testTargetAttributesAreStoredCorrectly() public function testLoadInvalidResource() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $loader = new XliffFileLoader(); $loader->load(__DIR__.'/../fixtures/resources.php', 'en', 'domain1'); } public function testLoadResourceDoesNotValidate() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $loader = new XliffFileLoader(); $loader->load(__DIR__.'/../fixtures/non-valid.xlf', 'en', 'domain1'); } public function testLoadNonExistingResource() { - $this->expectException(\Symfony\Component\Translation\Exception\NotFoundResourceException::class); + $this->expectException(NotFoundResourceException::class); $loader = new XliffFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.xlf'; $loader->load($resource, 'en', 'domain1'); @@ -134,7 +136,7 @@ public function testLoadNonExistingResource() public function testLoadThrowsAnExceptionIfFileNotLocal() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $loader = new XliffFileLoader(); $resource = 'http://example.com/resources.xlf'; $loader->load($resource, 'en', 'domain1'); @@ -142,7 +144,7 @@ public function testLoadThrowsAnExceptionIfFileNotLocal() public function testDocTypeIsNotAllowed() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $this->expectExceptionMessage('Document types are not allowed.'); $loader = new XliffFileLoader(); $loader->load(__DIR__.'/../fixtures/withdoctype.xlf', 'en', 'domain1'); @@ -153,7 +155,7 @@ public function testParseEmptyFile() $loader = new XliffFileLoader(); $resource = __DIR__.'/../fixtures/empty.xlf'; - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $this->expectExceptionMessage(sprintf('Unable to load "%s":', $resource)); $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.php index f1e6f4aece11..230c02e539e4 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Translation\Exception\InvalidResourceException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; use Symfony\Component\Translation\Loader\YamlFileLoader; class YamlFileLoaderTest extends TestCase @@ -41,7 +43,7 @@ public function testLoadDoesNothingIfEmpty() public function testLoadNonExistingResource() { - $this->expectException(\Symfony\Component\Translation\Exception\NotFoundResourceException::class); + $this->expectException(NotFoundResourceException::class); $loader = new YamlFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.yml'; $loader->load($resource, 'en', 'domain1'); @@ -49,7 +51,7 @@ public function testLoadNonExistingResource() public function testLoadThrowsAnExceptionIfFileNotLocal() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $loader = new YamlFileLoader(); $resource = 'http://example.com/resources.yml'; $loader->load($resource, 'en', 'domain1'); @@ -57,7 +59,7 @@ public function testLoadThrowsAnExceptionIfFileNotLocal() public function testLoadThrowsAnExceptionIfNotAnArray() { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidResourceException::class); + $this->expectException(InvalidResourceException::class); $loader = new YamlFileLoader(); $resource = __DIR__.'/../fixtures/non-valid.yml'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/LoggingTranslatorTest.php b/src/Symfony/Component/Translation/Tests/LoggingTranslatorTest.php index 668fb9d7e826..fb9906144a85 100644 --- a/src/Symfony/Component/Translation/Tests/LoggingTranslatorTest.php +++ b/src/Symfony/Component/Translation/Tests/LoggingTranslatorTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Translation\Tests; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; use Symfony\Component\Translation\Loader\ArrayLoader; use Symfony\Component\Translation\LoggingTranslator; use Symfony\Component\Translation\Translator; @@ -20,7 +21,7 @@ class LoggingTranslatorTest extends TestCase { public function testTransWithNoTranslationIsLogged() { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $logger->expects($this->exactly(1)) ->method('warning') ->with('Translation not found.') @@ -36,7 +37,7 @@ public function testTransWithNoTranslationIsLogged() */ public function testTransChoiceFallbackIsLogged() { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $logger->expects($this->once()) ->method('debug') ->with('Translation use fallback catalogue.') @@ -55,7 +56,7 @@ public function testTransChoiceFallbackIsLogged() */ public function testTransChoiceWithNoTranslationIsLogged() { - $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class)->getMock(); + $logger = $this->createMock(LoggerInterface::class); $logger->expects($this->exactly(1)) ->method('warning') ->with('Translation not found.') diff --git a/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php b/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php index 31d550406dfe..89784fe7f417 100644 --- a/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php +++ b/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\Translation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Resource\ResourceInterface; +use Symfony\Component\Translation\Exception\LogicException; use Symfony\Component\Translation\MessageCatalogue; class MessageCatalogueTest extends TestCase @@ -137,10 +139,10 @@ public function testReplace() public function testAddCatalogue() { - $r = $this->getMockBuilder(\Symfony\Component\Config\Resource\ResourceInterface::class)->getMock(); + $r = $this->createMock(ResourceInterface::class); $r->expects($this->any())->method('__toString')->willReturn('r'); - $r1 = $this->getMockBuilder(\Symfony\Component\Config\Resource\ResourceInterface::class)->getMock(); + $r1 = $this->createMock(ResourceInterface::class); $r1->expects($this->any())->method('__toString')->willReturn('r1'); $catalogue = new MessageCatalogue('en', ['domain1' => ['foo' => 'foo']]); @@ -161,13 +163,13 @@ public function testAddCatalogue() public function testAddFallbackCatalogue() { - $r = $this->getMockBuilder(\Symfony\Component\Config\Resource\ResourceInterface::class)->getMock(); + $r = $this->createMock(ResourceInterface::class); $r->expects($this->any())->method('__toString')->willReturn('r'); - $r1 = $this->getMockBuilder(\Symfony\Component\Config\Resource\ResourceInterface::class)->getMock(); + $r1 = $this->createMock(ResourceInterface::class); $r1->expects($this->any())->method('__toString')->willReturn('r1'); - $r2 = $this->getMockBuilder(\Symfony\Component\Config\Resource\ResourceInterface::class)->getMock(); + $r2 = $this->createMock(ResourceInterface::class); $r2->expects($this->any())->method('__toString')->willReturn('r2'); $catalogue = new MessageCatalogue('fr_FR', ['domain1' => ['foo' => 'foo'], 'domain2' => ['bar' => 'bar']]); @@ -190,7 +192,7 @@ public function testAddFallbackCatalogue() public function testAddFallbackCatalogueWithParentCircularReference() { - $this->expectException(\Symfony\Component\Translation\Exception\LogicException::class); + $this->expectException(LogicException::class); $main = new MessageCatalogue('en_US'); $fallback = new MessageCatalogue('fr_FR'); @@ -200,7 +202,7 @@ public function testAddFallbackCatalogueWithParentCircularReference() public function testAddFallbackCatalogueWithFallbackCircularReference() { - $this->expectException(\Symfony\Component\Translation\Exception\LogicException::class); + $this->expectException(LogicException::class); $fr = new MessageCatalogue('fr'); $en = new MessageCatalogue('en'); $es = new MessageCatalogue('es'); @@ -212,7 +214,7 @@ public function testAddFallbackCatalogueWithFallbackCircularReference() public function testAddCatalogueWhenLocaleIsNotTheSameAsTheCurrentOne() { - $this->expectException(\Symfony\Component\Translation\Exception\LogicException::class); + $this->expectException(LogicException::class); $catalogue = new MessageCatalogue('en'); $catalogue->addCatalogue(new MessageCatalogue('fr', [])); } @@ -220,11 +222,11 @@ public function testAddCatalogueWhenLocaleIsNotTheSameAsTheCurrentOne() public function testGetAddResource() { $catalogue = new MessageCatalogue('en'); - $r = $this->getMockBuilder(\Symfony\Component\Config\Resource\ResourceInterface::class)->getMock(); + $r = $this->createMock(ResourceInterface::class); $r->expects($this->any())->method('__toString')->willReturn('r'); $catalogue->addResource($r); $catalogue->addResource($r); - $r1 = $this->getMockBuilder(\Symfony\Component\Config\Resource\ResourceInterface::class)->getMock(); + $r1 = $this->createMock(ResourceInterface::class); $r1->expects($this->any())->method('__toString')->willReturn('r1'); $catalogue->addResource($r1); diff --git a/src/Symfony/Component/Translation/Tests/MessageSelectorTest.php b/src/Symfony/Component/Translation/Tests/MessageSelectorTest.php index 1e67878e1f85..ed88a9eb7d0e 100644 --- a/src/Symfony/Component/Translation/Tests/MessageSelectorTest.php +++ b/src/Symfony/Component/Translation/Tests/MessageSelectorTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Translation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Translation\Exception\InvalidArgumentException; use Symfony\Component\Translation\MessageSelector; /** @@ -41,7 +42,7 @@ public function testReturnMessageIfExactlyOneStandardRuleIsGiven() */ public function testThrowExceptionIfMatchingMessageCannotBeFound($id, $number) { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $selector = new MessageSelector(); $selector->choose($id, $number, 'en'); diff --git a/src/Symfony/Component/Translation/Tests/TranslatorCacheTest.php b/src/Symfony/Component/Translation/Tests/TranslatorCacheTest.php index a523b2bbaed5..a4906878335d 100644 --- a/src/Symfony/Component/Translation/Tests/TranslatorCacheTest.php +++ b/src/Symfony/Component/Translation/Tests/TranslatorCacheTest.php @@ -101,7 +101,7 @@ public function testCatalogueIsReloadedWhenResourcesAreNoLongerFresh() $catalogue->addResource(new StaleResource()); // better use a helper class than a mock, because it gets serialized in the cache and re-loaded /** @var LoaderInterface|MockObject $loader */ - $loader = $this->getMockBuilder(LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loader ->expects($this->exactly(2)) ->method('load') @@ -248,8 +248,8 @@ public function testPrimaryAndFallbackCataloguesContainTheSameMessagesRegardless public function testRefreshCacheWhenResourcesAreNoLongerFresh() { - $resource = $this->getMockBuilder(SelfCheckingResourceInterface::class)->getMock(); - $loader = $this->getMockBuilder(LoaderInterface::class)->getMock(); + $resource = $this->createMock(SelfCheckingResourceInterface::class); + $loader = $this->createMock(LoaderInterface::class); $resource->method('isFresh')->willReturn(false); $loader ->expects($this->exactly(2)) @@ -305,7 +305,7 @@ public function runForDebugAndProduction() private function createFailingLoader(): LoaderInterface { - $loader = $this->getMockBuilder(LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $loader ->expects($this->never()) ->method('load'); diff --git a/src/Symfony/Component/Translation/Tests/TranslatorTest.php b/src/Symfony/Component/Translation/Tests/TranslatorTest.php index bfe5cd9ab867..742956c0a97d 100644 --- a/src/Symfony/Component/Translation/Tests/TranslatorTest.php +++ b/src/Symfony/Component/Translation/Tests/TranslatorTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\Translation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\Translation\Exception\InvalidArgumentException; +use Symfony\Component\Translation\Exception\NotFoundResourceException; use Symfony\Component\Translation\Exception\RuntimeException; use Symfony\Component\Translation\Loader\ArrayLoader; use Symfony\Component\Translation\MessageCatalogue; @@ -37,7 +39,7 @@ protected function tearDown(): void */ public function testConstructorInvalidLocale($locale) { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); new Translator($locale); } @@ -76,7 +78,7 @@ public function testSetGetLocale() */ public function testSetInvalidLocale($locale) { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $translator = new Translator('fr'); $translator->setLocale($locale); } @@ -170,7 +172,7 @@ public function testSetFallbackLocalesMultiple() */ public function testSetFallbackInvalidLocales($locale) { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $translator = new Translator('fr'); $translator->setFallbackLocales(['fr', $locale]); } @@ -213,7 +215,7 @@ public function testTransWithFallbackLocale() */ public function testAddResourceInvalidLocales($locale) { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $translator = new Translator('fr'); $translator->addResource('array', ['foo' => 'foofoo'], $locale); } @@ -258,7 +260,7 @@ public function testAddResourceAfterTrans() */ public function testTransWithoutFallbackLocaleFile($format, $loader) { - $this->expectException(\Symfony\Component\Translation\Exception\NotFoundResourceException::class); + $this->expectException(NotFoundResourceException::class); $loaderClass = 'Symfony\\Component\\Translation\\Loader\\'.$loader; $translator = new Translator('en'); $translator->addLoader($format, new $loaderClass()); @@ -428,7 +430,7 @@ public function testTrans($expected, $id, $translation, $parameters, $locale, $d */ public function testTransInvalidLocale($locale) { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); $translator->addResource('array', ['foo' => 'foofoo'], 'en'); @@ -491,7 +493,7 @@ public function testTransChoice($expected, $id, $translation, $number, $paramete */ public function testTransChoiceInvalidLocale($locale) { - $this->expectException(\Symfony\Component\Translation\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); $translator->addResource('array', ['foo' => 'foofoo'], 'en'); diff --git a/src/Symfony/Component/Translation/Tests/Writer/TranslationWriterTest.php b/src/Symfony/Component/Translation/Tests/Writer/TranslationWriterTest.php index 9567f71db8c4..cd6fb3f622b0 100644 --- a/src/Symfony/Component/Translation/Tests/Writer/TranslationWriterTest.php +++ b/src/Symfony/Component/Translation/Tests/Writer/TranslationWriterTest.php @@ -20,7 +20,7 @@ class TranslationWriterTest extends TestCase { public function testWrite() { - $dumper = $this->getMockBuilder(DumperInterface::class)->getMock(); + $dumper = $this->createMock(DumperInterface::class); $dumper ->expects($this->once()) ->method('dump'); diff --git a/src/Symfony/Component/Validator/Test/ConstraintValidatorTestCase.php b/src/Symfony/Component/Validator/Test/ConstraintValidatorTestCase.php index d46cb26cec4e..b5c263aca729 100644 --- a/src/Symfony/Component/Validator/Test/ConstraintValidatorTestCase.php +++ b/src/Symfony/Component/Validator/Test/ConstraintValidatorTestCase.php @@ -28,6 +28,7 @@ use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Mapping\PropertyMetadata; use Symfony\Component\Validator\Validator\ContextualValidatorInterface; +use Symfony\Component\Validator\Validator\ValidatorInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** @@ -105,9 +106,9 @@ protected function restoreDefaultTimezone() protected function createContext() { - $translator = $this->getMockBuilder(TranslatorInterface::class)->getMock(); + $translator = $this->createMock(TranslatorInterface::class); $translator->expects($this->any())->method('trans')->willReturnArgument(0); - $validator = $this->getMockBuilder(\Symfony\Component\Validator\Validator\ValidatorInterface::class)->getMock(); + $validator = $this->createMock(ValidatorInterface::class); $context = new ExecutionContext($validator, $this->root, $translator); $context->setGroup($this->group); diff --git a/src/Symfony/Component/Validator/Tests/ConstraintTest.php b/src/Symfony/Component/Validator/Tests/ConstraintTest.php index 23466dd4ffce..66c9f5e3c13f 100644 --- a/src/Symfony/Component/Validator/Tests/ConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/ConstraintTest.php @@ -13,7 +13,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraint; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; +use Symfony\Component\Validator\Exception\InvalidArgumentException; use Symfony\Component\Validator\Exception\InvalidOptionsException; +use Symfony\Component\Validator\Exception\MissingOptionsException; use Symfony\Component\Validator\Tests\Fixtures\ClassConstraint; use Symfony\Component\Validator\Tests\Fixtures\ConstraintA; use Symfony\Component\Validator\Tests\Fixtures\ConstraintB; @@ -104,14 +107,14 @@ public function testDontSetDefaultPropertyIfValuePropertyExists() public function testSetUndefinedDefaultProperty() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new ConstraintB('foo'); } public function testRequiredOptionsMustBeDefined() { - $this->expectException(\Symfony\Component\Validator\Exception\MissingOptionsException::class); + $this->expectException(MissingOptionsException::class); new ConstraintC(); } @@ -209,7 +212,7 @@ public function testSerializeKeepsCustomGroups() public function testGetErrorNameForUnknownCode() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); Constraint::getErrorName(1); } @@ -244,7 +247,7 @@ public function testOptionsWithInvalidInternalPointer() public function testAnnotationSetUndefinedDefaultOption() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('No default option is configured for constraint "Symfony\Component\Validator\Tests\Fixtures\ConstraintB".'); new ConstraintB(['value' => 1]); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AllTest.php b/src/Symfony/Component/Validator/Tests/Constraints/AllTest.php index 78e5b6010385..c91f06875e36 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/AllTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/AllTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\All; use Symfony\Component\Validator\Constraints\Valid; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; /** * @author Bernhard Schussek @@ -22,7 +23,7 @@ class AllTest extends TestCase { public function testRejectNonConstraints() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new All([ 'foo', ]); @@ -30,7 +31,7 @@ public function testRejectNonConstraints() public function testRejectValidConstraint() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new All([ new Valid(), ]); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php index fb7fd281bbf4..0daa82498af1 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php @@ -15,6 +15,7 @@ use Symfony\Component\Validator\Constraints\AllValidator; use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Validator\Constraints\Range; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class AllValidatorTest extends ConstraintValidatorTestCase @@ -33,7 +34,7 @@ public function testNullIsValid() public function testThrowsExceptionIfNotTraversable() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate('foo.barbar', new All(new Range(['min' => 4]))); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php index e1cf94c1756a..6895311b1f6c 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php @@ -14,6 +14,7 @@ use Symfony\Component\Validator\Constraints\Bic; use Symfony\Component\Validator\Constraints\BicValidator; use Symfony\Component\Validator\Exception\ConstraintDefinitionException; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class BicValidatorTest extends ConstraintValidatorTestCase @@ -129,7 +130,7 @@ public function testInvalidValuePath() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Bic()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php index 627da6702ef5..4f446ed67779 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php @@ -15,6 +15,7 @@ use Symfony\Component\Validator\Constraints\Callback; use Symfony\Component\Validator\Constraints\CallbackValidator; use Symfony\Component\Validator\Context\ExecutionContextInterface; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class CallbackValidatorTest_Class @@ -182,7 +183,7 @@ public function testArrayCallableExplicitName() public function testExpectValidMethods() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $object = new CallbackValidatorTest_Object(); $this->validator->validate($object, new Callback(['callback' => ['foobar']])); @@ -190,7 +191,7 @@ public function testExpectValidMethods() public function testExpectValidCallbacks() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $object = new CallbackValidatorTest_Object(); $this->validator->validate($object, new Callback(['callback' => ['foo', 'bar']])); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php index c5ea94984d7a..5a828229feda 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php @@ -13,6 +13,8 @@ use Symfony\Component\Validator\Constraints\Choice; use Symfony\Component\Validator\Constraints\ChoiceValidator; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; function choice_callback() @@ -39,7 +41,7 @@ public function objectMethodCallback() public function testExpectArrayIfMultipleIsTrue() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $constraint = new Choice([ 'choices' => ['foo', 'bar'], 'multiple' => true, @@ -62,13 +64,13 @@ public function testNullIsValid() public function testChoicesOrCallbackExpected() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->validator->validate('foobar', new Choice()); } public function testValidCallbackExpected() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->validator->validate('foobar', new Choice(['callback' => 'abcd'])); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php index 8a1c73e1f664..a362e96ceec8 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php @@ -17,6 +17,7 @@ use Symfony\Component\Validator\Constraints\Optional; use Symfony\Component\Validator\Constraints\Required; use Symfony\Component\Validator\Constraints\Valid; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; /** * @author Bernhard Schussek @@ -25,7 +26,7 @@ class CollectionTest extends TestCase { public function testRejectInvalidFieldsOption() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new Collection([ 'fields' => 'foo', ]); @@ -33,7 +34,7 @@ public function testRejectInvalidFieldsOption() public function testRejectNonConstraints() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new Collection([ 'foo' => 'bar', ]); @@ -41,7 +42,7 @@ public function testRejectNonConstraints() public function testRejectValidConstraint() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new Collection([ 'foo' => new Valid(), ]); @@ -49,7 +50,7 @@ public function testRejectValidConstraint() public function testRejectValidConstraintWithinOptional() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new Collection([ 'foo' => new Optional(new Valid()), ]); @@ -57,7 +58,7 @@ public function testRejectValidConstraintWithinOptional() public function testRejectValidConstraintWithinRequired() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new Collection([ 'foo' => new Required(new Valid()), ]); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php index effac4156cde..64fa81f839e0 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php @@ -17,6 +17,7 @@ use Symfony\Component\Validator\Constraints\Optional; use Symfony\Component\Validator\Constraints\Range; use Symfony\Component\Validator\Constraints\Required; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; abstract class CollectionValidatorTest extends ConstraintValidatorTestCase @@ -54,7 +55,7 @@ public function testFieldsAsDefaultOption() public function testThrowsExceptionIfNotTraversable() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate('foobar', new Collection(['fields' => [ 'foo' => new Range(['min' => 4]), ]])); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CompositeTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CompositeTest.php index 69466d3d53c8..b0236c3ec152 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CompositeTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CompositeTest.php @@ -16,6 +16,7 @@ use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Validator\Constraints\Valid; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; class ConcreteComposite extends Composite { @@ -105,7 +106,7 @@ public function testExplicitNestedGroupsMustBeSubsetOfExplicitParentGroups() public function testFailIfExplicitNestedGroupsNotSubsetOfExplicitParentGroups() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new ConcreteComposite([ 'constraints' => [ new NotNull(['groups' => ['Default', 'Foobar']]), @@ -138,7 +139,7 @@ public function testSingleConstraintsAccepted() public function testFailIfNoConstraint() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new ConcreteComposite([ new NotNull(['groups' => 'Default']), 'NotBlank', @@ -147,7 +148,7 @@ public function testFailIfNoConstraint() public function testFailIfNoConstraintObject() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new ConcreteComposite([ new NotNull(['groups' => 'Default']), new \ArrayObject(), @@ -156,7 +157,7 @@ public function testFailIfNoConstraintObject() public function testValidCantBeNested() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new ConcreteComposite([ new Valid(), ]); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php index 74738b32c842..78296201b284 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Validator\Constraints\Count; use Symfony\Component\Validator\Constraints\CountValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; /** @@ -36,7 +37,7 @@ public function testNullIsValid() public function testExpectsCountableType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Count(5)); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php index f2b07bc594ab..8c5adbb78ee6 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php @@ -14,6 +14,7 @@ use Symfony\Component\Intl\Util\IntlTestHelper; use Symfony\Component\Validator\Constraints\Country; use Symfony\Component\Validator\Constraints\CountryValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class CountryValidatorTest extends ConstraintValidatorTestCase @@ -55,7 +56,7 @@ public function testEmptyStringIsValid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Country()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php index 997eaff22eea..11028e748bb6 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php @@ -14,6 +14,7 @@ use Symfony\Component\Intl\Util\IntlTestHelper; use Symfony\Component\Validator\Constraints\Currency; use Symfony\Component\Validator\Constraints\CurrencyValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class CurrencyValidatorTest extends ConstraintValidatorTestCase @@ -55,7 +56,7 @@ public function testEmptyStringIsValid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Currency()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php index 0f736a7abbf8..6ef48ae42ed3 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Validator\Constraints\DateTime; use Symfony\Component\Validator\Constraints\DateTimeValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class DateTimeValidatorTest extends ConstraintValidatorTestCase @@ -60,7 +61,7 @@ public function testDateTimeImmutableClassIsValid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new DateTime()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php index 64fec4bb6798..11ff79d8fe03 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Validator\Constraints\Date; use Symfony\Component\Validator\Constraints\DateValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class DateValidatorTest extends ConstraintValidatorTestCase @@ -60,7 +61,7 @@ public function testDateTimeImmutableClassIsValid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Date()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/EmailTest.php b/src/Symfony/Component/Validator/Tests/Constraints/EmailTest.php index e80b3d8b944e..d90a6139ebda 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/EmailTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/EmailTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\Email; +use Symfony\Component\Validator\Exception\InvalidArgumentException; class EmailTest extends TestCase { @@ -36,7 +37,7 @@ public function testConstructorStrict() public function testUnknownModesTriggerException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "mode" parameter value is not valid.'); new Email(['mode' => 'Unknown Mode']); } @@ -50,14 +51,14 @@ public function testNormalizerCanBeSet() public function testInvalidNormalizerThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new Email(['normalizer' => 'Unknown Callable']); } public function testInvalidNormalizerObjectThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new Email(['normalizer' => new \stdClass()]); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php index c27a9020350a..45b8943cc1af 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php @@ -14,6 +14,7 @@ use Symfony\Bridge\PhpUnit\DnsMock; use Symfony\Component\Validator\Constraints\Email; use Symfony\Component\Validator\Constraints\EmailValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; /** @@ -69,7 +70,7 @@ public function testObjectEmptyStringIsValid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Email()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/ExpressionValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/ExpressionValidatorTest.php index 900d0743de6d..44ef9f70824d 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/ExpressionValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/ExpressionValidatorTest.php @@ -255,7 +255,7 @@ public function testExpressionLanguageUsage() 'expression' => 'false', ]); - $expressionLanguage = $this->getMockBuilder(ExpressionLanguage::class)->getMock(); + $expressionLanguage = $this->createMock(ExpressionLanguage::class); $used = false; @@ -283,7 +283,7 @@ public function testLegacyExpressionLanguageUsage() 'expression' => 'false', ]); - $expressionLanguage = $this->getMockBuilder(ExpressionLanguage::class)->getMock(); + $expressionLanguage = $this->createMock(ExpressionLanguage::class); $used = false; diff --git a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php index d14374fe21cf..7178b07cf39e 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php @@ -14,6 +14,8 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\Validator\Constraints\File; use Symfony\Component\Validator\Constraints\FileValidator; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; abstract class FileValidatorTest extends ConstraintValidatorTestCase @@ -68,7 +70,7 @@ public function testEmptyStringIsValid() public function testExpectsStringCompatibleTypeOrFile() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new File()); } @@ -224,7 +226,7 @@ public function testMaxSizeNotExceeded($bytesWritten, $limit) public function testInvalidMaxSize() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $constraint = new File([ 'maxSize' => '1abc', ]); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorWithPositiveOrZeroConstraintTest.php b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorWithPositiveOrZeroConstraintTest.php index 4979487e4a0c..15f92b128b34 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorWithPositiveOrZeroConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorWithPositiveOrZeroConstraintTest.php @@ -14,6 +14,7 @@ use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\AbstractComparison; use Symfony\Component\Validator\Constraints\PositiveOrZero; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; /** * @author Jan Schädlich @@ -55,7 +56,7 @@ public function provideInvalidComparisons(): array public function testThrowsConstraintExceptionIfPropertyPath() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('The "propertyPath" option of the "Symfony\Component\Validator\Constraints\PositiveOrZero" constraint cannot be set.'); return new PositiveOrZero(['propertyPath' => 'field']); @@ -63,7 +64,7 @@ public function testThrowsConstraintExceptionIfPropertyPath() public function testThrowsConstraintExceptionIfValue() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('The "value" option of the "Symfony\Component\Validator\Constraints\PositiveOrZero" constraint cannot be set.'); return new PositiveOrZero(['value' => 0]); @@ -74,14 +75,14 @@ public function testThrowsConstraintExceptionIfValue() */ public function testThrowsConstraintExceptionIfNoValueOrPropertyPath($options) { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('requires either the "value" or "propertyPath" option to be set.'); $this->markTestSkipped('Value option always set for PositiveOrZero constraint'); } public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('requires only one of the "value" or "propertyPath" options to be set, not both.'); $this->markTestSkipped('Value option is set for PositiveOrZero constraint automatically'); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorWithPositiveConstraintTest.php b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorWithPositiveConstraintTest.php index 6fb8f4c92e43..f3855343a24e 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorWithPositiveConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorWithPositiveConstraintTest.php @@ -14,6 +14,7 @@ use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\AbstractComparison; use Symfony\Component\Validator\Constraints\Positive; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; /** * @author Jan Schädlich @@ -53,7 +54,7 @@ public function provideInvalidComparisons(): array public function testThrowsConstraintExceptionIfPropertyPath() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('The "propertyPath" option of the "Symfony\Component\Validator\Constraints\Positive" constraint cannot be set.'); return new Positive(['propertyPath' => 'field']); @@ -61,7 +62,7 @@ public function testThrowsConstraintExceptionIfPropertyPath() public function testThrowsConstraintExceptionIfValue() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('The "value" option of the "Symfony\Component\Validator\Constraints\Positive" constraint cannot be set.'); return new Positive(['value' => 0]); @@ -72,14 +73,14 @@ public function testThrowsConstraintExceptionIfValue() */ public function testThrowsConstraintExceptionIfNoValueOrPropertyPath($options) { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('requires either the "value" or "propertyPath" option to be set.'); $this->markTestSkipped('Value option always set for Positive constraint.'); } public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('requires only one of the "value" or "propertyPath" options to be set, not both.'); $this->markTestSkipped('Value option is set for Positive constraint automatically'); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php index 28050270f15a..5ae1e035225c 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Validator\Constraints\Image; use Symfony\Component\Validator\Constraints\ImageValidator; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; /** @@ -202,7 +203,7 @@ public function testPixelsTooMany() public function testInvalidMinWidth() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $constraint = new Image([ 'minWidth' => '1abc', ]); @@ -212,7 +213,7 @@ public function testInvalidMinWidth() public function testInvalidMaxWidth() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $constraint = new Image([ 'maxWidth' => '1abc', ]); @@ -222,7 +223,7 @@ public function testInvalidMaxWidth() public function testInvalidMinHeight() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $constraint = new Image([ 'minHeight' => '1abc', ]); @@ -232,7 +233,7 @@ public function testInvalidMinHeight() public function testInvalidMaxHeight() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $constraint = new Image([ 'maxHeight' => '1abc', ]); @@ -242,7 +243,7 @@ public function testInvalidMaxHeight() public function testInvalidMinPixels() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $constraint = new Image([ 'minPixels' => '1abc', ]); @@ -252,7 +253,7 @@ public function testInvalidMinPixels() public function testInvalidMaxPixels() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $constraint = new Image([ 'maxPixels' => '1abc', ]); @@ -305,7 +306,7 @@ public function testMaxRatioUsesTwoDecimalsOnly() public function testInvalidMinRatio() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $constraint = new Image([ 'minRatio' => '1abc', ]); @@ -315,7 +316,7 @@ public function testInvalidMinRatio() public function testInvalidMaxRatio() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $constraint = new Image([ 'maxRatio' => '1abc', ]); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IpTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IpTest.php index b0d9930fecb1..4b7d28b0a272 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IpTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IpTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\Ip; +use Symfony\Component\Validator\Exception\InvalidArgumentException; /** * @author Renan Taranto @@ -28,14 +29,14 @@ public function testNormalizerCanBeSet() public function testInvalidNormalizerThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new Ip(['normalizer' => 'Unknown Callable']); } public function testInvalidNormalizerObjectThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new Ip(['normalizer' => new \stdClass()]); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php index c3401b011be6..2b566a73e771 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php @@ -13,6 +13,8 @@ use Symfony\Component\Validator\Constraints\Ip; use Symfony\Component\Validator\Constraints\IpValidator; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class IpValidatorTest extends ConstraintValidatorTestCase @@ -38,13 +40,13 @@ public function testEmptyStringIsValid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Ip()); } public function testInvalidValidatorVersion() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new Ip([ 'version' => 666, ]); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php index 057c4d3c0410..7e80ce56f177 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Validator\Constraints\Isbn; use Symfony\Component\Validator\Constraints\IsbnValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; /** @@ -138,7 +139,7 @@ public function testEmptyStringIsValid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $constraint = new Isbn(true); $this->validator->validate(new \stdClass(), $constraint); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php index 52199b8d03c2..fa471fc71dba 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Validator\Constraints\Issn; use Symfony\Component\Validator\Constraints\IssnValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; /** @@ -108,7 +109,7 @@ public function testEmptyStringIsValid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $constraint = new Issn(); $this->validator->validate(new \stdClass(), $constraint); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php index 090b12207682..172b2f1444e6 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php @@ -14,6 +14,7 @@ use Symfony\Component\Intl\Util\IntlTestHelper; use Symfony\Component\Validator\Constraints\Language; use Symfony\Component\Validator\Constraints\LanguageValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class LanguageValidatorTest extends ConstraintValidatorTestCase @@ -55,7 +56,7 @@ public function testEmptyStringIsValid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Language()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LengthTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LengthTest.php index 0b8a14e85c65..1aff54e8b593 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LengthTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LengthTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\Length; +use Symfony\Component\Validator\Exception\InvalidArgumentException; /** * @author Renan Taranto @@ -28,14 +29,14 @@ public function testNormalizerCanBeSet() public function testInvalidNormalizerThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new Length(['min' => 0, 'max' => 10, 'normalizer' => 'Unknown Callable', 'allowEmptyString' => false]); } public function testInvalidNormalizerObjectThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new Length(['min' => 0, 'max' => 10, 'normalizer' => new \stdClass(), 'allowEmptyString' => false]); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php index c106a1e7181a..4392f3bcab80 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Validator\Constraints\Length; use Symfony\Component\Validator\Constraints\LengthValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class LengthValidatorTest extends ConstraintValidatorTestCase @@ -59,7 +60,7 @@ public function testEmptyStringIsInvalid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Length(['value' => 5, 'allowEmptyString' => false])); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorWithNegativeOrZeroConstraintTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorWithNegativeOrZeroConstraintTest.php index 92e9a3620c48..a59f3a91b4d6 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorWithNegativeOrZeroConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorWithNegativeOrZeroConstraintTest.php @@ -14,6 +14,7 @@ use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\AbstractComparison; use Symfony\Component\Validator\Constraints\NegativeOrZero; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; /** * @author Jan Schädlich @@ -53,7 +54,7 @@ public function provideInvalidComparisons(): array public function testThrowsConstraintExceptionIfPropertyPath() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('The "propertyPath" option of the "Symfony\Component\Validator\Constraints\NegativeOrZero" constraint cannot be set.'); return new NegativeOrZero(['propertyPath' => 'field']); @@ -61,7 +62,7 @@ public function testThrowsConstraintExceptionIfPropertyPath() public function testThrowsConstraintExceptionIfValue() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('The "value" option of the "Symfony\Component\Validator\Constraints\NegativeOrZero" constraint cannot be set.'); return new NegativeOrZero(['value' => 0]); @@ -72,14 +73,14 @@ public function testThrowsConstraintExceptionIfValue() */ public function testThrowsConstraintExceptionIfNoValueOrPropertyPath($options) { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('requires either the "value" or "propertyPath" option to be set.'); $this->markTestSkipped('Value option always set for NegativeOrZero constraint'); } public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('requires only one of the "value" or "propertyPath" options to be set, not both.'); $this->markTestSkipped('Value option is set for NegativeOrZero constraint automatically'); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorWithNegativeConstraintTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorWithNegativeConstraintTest.php index 7f7da277ae69..8bf8ea874e49 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorWithNegativeConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorWithNegativeConstraintTest.php @@ -14,6 +14,7 @@ use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\AbstractComparison; use Symfony\Component\Validator\Constraints\Negative; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; /** * @author Jan Schädlich @@ -53,7 +54,7 @@ public function provideInvalidComparisons(): array public function testThrowsConstraintExceptionIfPropertyPath() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('The "propertyPath" option of the "Symfony\Component\Validator\Constraints\Negative" constraint cannot be set.'); return new Negative(['propertyPath' => 'field']); @@ -61,7 +62,7 @@ public function testThrowsConstraintExceptionIfPropertyPath() public function testThrowsConstraintExceptionIfValue() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('The "value" option of the "Symfony\Component\Validator\Constraints\Negative" constraint cannot be set.'); return new Negative(['value' => 0]); @@ -72,14 +73,14 @@ public function testThrowsConstraintExceptionIfValue() */ public function testThrowsConstraintExceptionIfNoValueOrPropertyPath($options) { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('requires either the "value" or "propertyPath" option to be set.'); $this->markTestSkipped('Value option always set for Negative constraint'); } public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('requires only one of the "value" or "propertyPath" options to be set, not both.'); $this->markTestSkipped('Value option is set for Negative constraint automatically'); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php index 55a41274cfcc..d4d20f86eceb 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php @@ -13,6 +13,8 @@ use Symfony\Component\Validator\Constraints\Locale; use Symfony\Component\Validator\Constraints\LocaleValidator; +use Symfony\Component\Validator\Exception\UnexpectedTypeException; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class LocaleValidatorTest extends ConstraintValidatorTestCase @@ -68,13 +70,13 @@ public function testEmptyStringIsValid() */ public function testLegacyExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $this->validator->validate(new \stdClass(), new Locale()); } public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Locale(['canonicalize' => true])); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php index 11e144e60780..5dc15b41a970 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Validator\Constraints\Luhn; use Symfony\Component\Validator\Constraints\LuhnValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class LuhnValidatorTest extends ConstraintValidatorTestCase @@ -103,7 +104,7 @@ public function getInvalidNumbers() */ public function testInvalidTypes($number) { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $constraint = new Luhn(); $this->validator->validate($number, $constraint); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NotBlankTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NotBlankTest.php index fe6597ceecc0..73993e541b62 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NotBlankTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NotBlankTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\NotBlank; +use Symfony\Component\Validator\Exception\InvalidArgumentException; /** * @author Renan Taranto @@ -28,14 +29,14 @@ public function testNormalizerCanBeSet() public function testInvalidNormalizerThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new NotBlank(['normalizer' => 'Unknown Callable']); } public function testInvalidNormalizerObjectThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new NotBlank(['normalizer' => new \stdClass()]); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NotCompromisedPasswordValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NotCompromisedPasswordValidatorTest.php index 3f34b008c0bd..32ce12ff4826 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NotCompromisedPasswordValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NotCompromisedPasswordValidatorTest.php @@ -14,7 +14,9 @@ use Symfony\Component\Validator\Constraints\Luhn; use Symfony\Component\Validator\Constraints\NotCompromisedPassword; use Symfony\Component\Validator\Constraints\NotCompromisedPasswordValidator; +use Symfony\Component\Validator\Exception\UnexpectedTypeException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; +use Symfony\Contracts\HttpClient\Exception\ExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; use Symfony\Contracts\HttpClient\ResponseInterface; @@ -153,19 +155,19 @@ public function testInvalidPasswordCustomEndpoint() public function testInvalidConstraint() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $this->validator->validate(null, new Luhn()); } public function testInvalidValue() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedTypeException::class); + $this->expectException(UnexpectedTypeException::class); $this->validator->validate([], new NotCompromisedPassword()); } public function testApiError() { - $this->expectException(\Symfony\Contracts\HttpClient\Exception\ExceptionInterface::class); + $this->expectException(ExceptionInterface::class); $this->expectExceptionMessage('Problem contacting the Have I been Pwned API.'); $this->validator->validate(self::PASSWORD_TRIGGERING_AN_ERROR, new NotCompromisedPassword()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/RangeTest.php b/src/Symfony/Component/Validator/Tests/Constraints/RangeTest.php index f9204858d218..ad8ef277da83 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/RangeTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/RangeTest.php @@ -4,12 +4,14 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\Range; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; +use Symfony\Component\Validator\Exception\MissingOptionsException; class RangeTest extends TestCase { public function testThrowsConstraintExceptionIfBothMinLimitAndPropertyPath() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('requires only one of the "min" or "minPropertyPath" options to be set, not both.'); new Range([ 'min' => 'min', @@ -19,7 +21,7 @@ public function testThrowsConstraintExceptionIfBothMinLimitAndPropertyPath() public function testThrowsConstraintExceptionIfBothMaxLimitAndPropertyPath() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('requires only one of the "max" or "maxPropertyPath" options to be set, not both.'); new Range([ 'max' => 'max', @@ -29,14 +31,14 @@ public function testThrowsConstraintExceptionIfBothMaxLimitAndPropertyPath() public function testThrowsConstraintExceptionIfNoLimitNorPropertyPath() { - $this->expectException(\Symfony\Component\Validator\Exception\MissingOptionsException::class); + $this->expectException(MissingOptionsException::class); $this->expectExceptionMessage('Either option "min", "minPropertyPath", "max" or "maxPropertyPath" must be given'); new Range([]); } public function testThrowsNoDefaultOptionConfiguredException() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('No default option is configured'); new Range('value'); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/RegexTest.php b/src/Symfony/Component/Validator/Tests/Constraints/RegexTest.php index bca27fa47765..10e485c368fe 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/RegexTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/RegexTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\Regex; +use Symfony\Component\Validator\Exception\InvalidArgumentException; /** * @author Bernhard Schussek @@ -95,14 +96,14 @@ public function testNormalizerCanBeSet() public function testInvalidNormalizerThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new Regex(['pattern' => '/^[0-9]+$/', 'normalizer' => 'Unknown Callable']); } public function testInvalidNormalizerObjectThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new Regex(['pattern' => '/^[0-9]+$/', 'normalizer' => new \stdClass()]); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php index 9eb736a0a672..601cdb701c17 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Validator\Constraints\Regex; use Symfony\Component\Validator\Constraints\RegexValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class RegexValidatorTest extends ConstraintValidatorTestCase @@ -38,7 +39,7 @@ public function testEmptyStringIsValid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Regex(['pattern' => '/^[0-9]+$/'])); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php index b98c17dec9b7..3a42e1bdff79 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Validator\Constraints\Time; use Symfony\Component\Validator\Constraints\TimeValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class TimeValidatorTest extends ConstraintValidatorTestCase @@ -49,7 +50,7 @@ public function testDateTimeClassIsValid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Time()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/TimezoneTest.php b/src/Symfony/Component/Validator/Tests/Constraints/TimezoneTest.php index 2801fe2160b9..f7b111494a7c 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/TimezoneTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/TimezoneTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\Timezone; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; /** * @author Javier Spagnoletti @@ -34,7 +35,7 @@ public function testValidTimezoneConstraints() public function testExceptionForGroupedTimezonesByCountryWithWrongZone() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new Timezone([ 'zone' => \DateTimeZone::ALL, 'countryCode' => 'AR', @@ -43,7 +44,7 @@ public function testExceptionForGroupedTimezonesByCountryWithWrongZone() public function testExceptionForGroupedTimezonesByCountryWithoutZone() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new Timezone(['countryCode' => 'AR']); } @@ -52,7 +53,7 @@ public function testExceptionForGroupedTimezonesByCountryWithoutZone() */ public function testExceptionForInvalidGroupedTimezones(int $zone) { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); new Timezone(['zone' => $zone]); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/TimezoneValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/TimezoneValidatorTest.php index 70f2f88f8738..a86a430e8320 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/TimezoneValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/TimezoneValidatorTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Validator\Constraints\Timezone; use Symfony\Component\Validator\Constraints\TimezoneValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; /** @@ -42,7 +43,7 @@ public function testEmptyStringIsValid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Timezone()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UniqueValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UniqueValidatorTest.php index 6d11b1fcc9ac..9478e6746990 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UniqueValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UniqueValidatorTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Validator\Constraints\Unique; use Symfony\Component\Validator\Constraints\UniqueValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class UniqueValidatorTest extends ConstraintValidatorTestCase @@ -24,7 +25,7 @@ protected function createValidator() public function testExpectsUniqueConstraintCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate('', new Unique()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UrlTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UrlTest.php index 3353d7f03ec8..cdf310999a75 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UrlTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UrlTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\Url; +use Symfony\Component\Validator\Exception\InvalidArgumentException; /** * @author Renan Taranto @@ -28,14 +29,14 @@ public function testNormalizerCanBeSet() public function testInvalidNormalizerThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new Url(['normalizer' => 'Unknown Callable']); } public function testInvalidNormalizerObjectThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new Url(['normalizer' => new \stdClass()]); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php index d232043c768d..e154c6b2df9c 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php @@ -14,6 +14,8 @@ use Symfony\Bridge\PhpUnit\DnsMock; use Symfony\Component\Validator\Constraints\Url; use Symfony\Component\Validator\Constraints\UrlValidator; +use Symfony\Component\Validator\Exception\InvalidOptionsException; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; /** @@ -49,7 +51,7 @@ public function testEmptyStringFromObjectIsValid() public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Url()); } @@ -367,7 +369,7 @@ public function getCheckDnsTypes() */ public function testCheckDnsWithInvalidType() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidOptionsException::class); + $this->expectException(InvalidOptionsException::class); DnsMock::withMockedHosts(['example.com' => [['type' => 'A']]]); $constraint = new Url([ diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UuidTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UuidTest.php index 78bd4a5e5227..89b2e7ef911b 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UuidTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UuidTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\Uuid; +use Symfony\Component\Validator\Exception\InvalidArgumentException; /** * @author Renan Taranto @@ -28,14 +29,14 @@ public function testNormalizerCanBeSet() public function testInvalidNormalizerThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new Uuid(['normalizer' => 'Unknown Callable']); } public function testInvalidNormalizerObjectThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new Uuid(['normalizer' => new \stdClass()]); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UuidValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UuidValidatorTest.php index ac2b7fe21300..db48ca7e7caf 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UuidValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UuidValidatorTest.php @@ -11,8 +11,11 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\Uuid; use Symfony\Component\Validator\Constraints\UuidValidator; +use Symfony\Component\Validator\Exception\UnexpectedTypeException; +use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; /** @@ -41,15 +44,15 @@ public function testEmptyStringIsValid() public function testExpectsUuidConstraintCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedTypeException::class); - $constraint = $this->getMockForAbstractClass(\Symfony\Component\Validator\Constraint::class); + $this->expectException(UnexpectedTypeException::class); + $constraint = $this->getMockForAbstractClass(Constraint::class); $this->validator->validate('216fff40-98d9-11e3-a5e2-0800200c9a66', $constraint); } public function testExpectsStringCompatibleType() { - $this->expectException(\Symfony\Component\Validator\Exception\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); $this->validator->validate(new \stdClass(), new Uuid()); } diff --git a/src/Symfony/Component/Validator/Tests/ContainerConstraintValidatorFactoryTest.php b/src/Symfony/Component/Validator/Tests/ContainerConstraintValidatorFactoryTest.php index 4555fcecbeeb..3999b86b4f19 100644 --- a/src/Symfony/Component/Validator/Tests/ContainerConstraintValidatorFactoryTest.php +++ b/src/Symfony/Component/Validator/Tests/ContainerConstraintValidatorFactoryTest.php @@ -17,6 +17,7 @@ use Symfony\Component\Validator\Constraints\Blank as BlankConstraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\ContainerConstraintValidatorFactory; +use Symfony\Component\Validator\Exception\ValidatorException; class ContainerConstraintValidatorFactoryTest extends TestCase { @@ -47,8 +48,8 @@ public function testGetInstanceReturnsService() public function testGetInstanceInvalidValidatorClass() { - $this->expectException(\Symfony\Component\Validator\Exception\ValidatorException::class); - $constraint = $this->getMockBuilder(Constraint::class)->getMock(); + $this->expectException(ValidatorException::class); + $constraint = $this->createMock(Constraint::class); $constraint ->expects($this->once()) ->method('validatedBy') diff --git a/src/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.php b/src/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.php index 04a7d1dff686..d8aa66cc2672 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.php @@ -14,8 +14,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\Composite; +use Symfony\Component\Validator\Constraints\GroupSequence; use Symfony\Component\Validator\Constraints\Valid; use Symfony\Component\Validator\Exception\ConstraintDefinitionException; +use Symfony\Component\Validator\Exception\GroupDefinitionException; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Tests\Fixtures\ClassConstraint; use Symfony\Component\Validator\Tests\Fixtures\ConstraintA; @@ -264,24 +266,24 @@ public function testGroupSequencesWorkIfContainingDefaultGroup() { $this->metadata->setGroupSequence(['Foo', $this->metadata->getDefaultGroup()]); - $this->assertInstanceOf(\Symfony\Component\Validator\Constraints\GroupSequence::class, $this->metadata->getGroupSequence()); + $this->assertInstanceOf(GroupSequence::class, $this->metadata->getGroupSequence()); } public function testGroupSequencesFailIfNotContainingDefaultGroup() { - $this->expectException(\Symfony\Component\Validator\Exception\GroupDefinitionException::class); + $this->expectException(GroupDefinitionException::class); $this->metadata->setGroupSequence(['Foo', 'Bar']); } public function testGroupSequencesFailIfContainingDefault() { - $this->expectException(\Symfony\Component\Validator\Exception\GroupDefinitionException::class); + $this->expectException(GroupDefinitionException::class); $this->metadata->setGroupSequence(['Foo', $this->metadata->getDefaultGroup(), Constraint::DEFAULT_GROUP]); } public function testGroupSequenceFailsIfGroupSequenceProviderIsSet() { - $this->expectException(\Symfony\Component\Validator\Exception\GroupDefinitionException::class); + $this->expectException(GroupDefinitionException::class); $metadata = new ClassMetadata(self::PROVIDERCLASS); $metadata->setGroupSequenceProvider(true); $metadata->setGroupSequence(['GroupSequenceProviderEntity', 'Foo']); @@ -289,7 +291,7 @@ public function testGroupSequenceFailsIfGroupSequenceProviderIsSet() public function testGroupSequenceProviderFailsIfGroupSequenceIsSet() { - $this->expectException(\Symfony\Component\Validator\Exception\GroupDefinitionException::class); + $this->expectException(GroupDefinitionException::class); $metadata = new ClassMetadata(self::PROVIDERCLASS); $metadata->setGroupSequence(['GroupSequenceProviderEntity', 'Foo']); $metadata->setGroupSequenceProvider(true); @@ -297,7 +299,7 @@ public function testGroupSequenceProviderFailsIfGroupSequenceIsSet() public function testGroupSequenceProviderFailsIfDomainClassIsInvalid() { - $this->expectException(\Symfony\Component\Validator\Exception\GroupDefinitionException::class); + $this->expectException(GroupDefinitionException::class); $metadata = new ClassMetadata('stdClass'); $metadata->setGroupSequenceProvider(true); } diff --git a/src/Symfony/Component/Validator/Tests/Mapping/Factory/BlackHoleMetadataFactoryTest.php b/src/Symfony/Component/Validator/Tests/Mapping/Factory/BlackHoleMetadataFactoryTest.php index 6cbfadad5b2f..549bc518b41b 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/Factory/BlackHoleMetadataFactoryTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/Factory/BlackHoleMetadataFactoryTest.php @@ -12,13 +12,14 @@ namespace Symfony\Component\Validator\Tests\Mapping\Factory; use PHPUnit\Framework\TestCase; +use Symfony\Component\Validator\Exception\LogicException; use Symfony\Component\Validator\Mapping\Factory\BlackHoleMetadataFactory; class BlackHoleMetadataFactoryTest extends TestCase { public function testGetMetadataForThrowsALogicException() { - $this->expectException(\Symfony\Component\Validator\Exception\LogicException::class); + $this->expectException(LogicException::class); $metadataFactory = new BlackHoleMetadataFactory(); $metadataFactory->getMetadataFor('foo'); } diff --git a/src/Symfony/Component/Validator/Tests/Mapping/Factory/LazyLoadingMetadataFactoryTest.php b/src/Symfony/Component/Validator/Tests/Mapping/Factory/LazyLoadingMetadataFactoryTest.php index 20a35e0632cd..bc9cfed834e7 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/Factory/LazyLoadingMetadataFactoryTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/Factory/LazyLoadingMetadataFactoryTest.php @@ -16,6 +16,8 @@ use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Validator\Constraints\Callback; use Symfony\Component\Validator\Constraints\NotBlank; +use Symfony\Component\Validator\Exception\NoSuchMetadataException; +use Symfony\Component\Validator\Mapping\Cache\CacheInterface; use Symfony\Component\Validator\Mapping\Cache\Psr6Cache; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory; @@ -131,8 +133,8 @@ public function testWriteMetadataToLegacyCache() */ public function testReadMetadataFromLegacyCache() { - $loader = $this->getMockBuilder(LoaderInterface::class)->getMock(); - $cache = $this->getMockBuilder(\Symfony\Component\Validator\Mapping\Cache\CacheInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); + $cache = $this->createMock(CacheInterface::class); $factory = new LazyLoadingMetadataFactory($loader, $cache); $metadata = new ClassMetadata(self::PARENT_CLASS); @@ -165,9 +167,9 @@ public function testReadMetadataFromLegacyCache() public function testNonClassNameStringValues() { - $this->expectException(\Symfony\Component\Validator\Exception\NoSuchMetadataException::class); + $this->expectException(NoSuchMetadataException::class); $testedValue = 'error@example.com'; - $loader = $this->getMockBuilder(LoaderInterface::class)->getMock(); + $loader = $this->createMock(LoaderInterface::class); $cache = $this->createMock(CacheItemPoolInterface::class); $factory = new LazyLoadingMetadataFactory($loader, $cache); $cache diff --git a/src/Symfony/Component/Validator/Tests/Mapping/GetterMetadataTest.php b/src/Symfony/Component/Validator/Tests/Mapping/GetterMetadataTest.php index 004b1df2b443..de5bc79ef282 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/GetterMetadataTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/GetterMetadataTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Validator\Tests\Mapping; use PHPUnit\Framework\TestCase; +use Symfony\Component\Validator\Exception\ValidatorException; use Symfony\Component\Validator\Mapping\GetterMetadata; use Symfony\Component\Validator\Tests\Fixtures\Entity; @@ -21,7 +22,7 @@ class GetterMetadataTest extends TestCase public function testInvalidPropertyName() { - $this->expectException(\Symfony\Component\Validator\Exception\ValidatorException::class); + $this->expectException(ValidatorException::class); new GetterMetadata(self::CLASSNAME, 'foobar'); } @@ -63,7 +64,7 @@ public function testGetPropertyValueFromHasser() public function testUndefinedMethodNameThrowsException() { - $this->expectException(\Symfony\Component\Validator\Exception\ValidatorException::class); + $this->expectException(ValidatorException::class); $this->expectExceptionMessage('The "hasLastName()" method does not exist in class "Symfony\Component\Validator\Tests\Fixtures\Entity".'); new GetterMetadata(self::CLASSNAME, 'lastName', 'hasLastName'); } diff --git a/src/Symfony/Component/Validator/Tests/Mapping/Loader/FilesLoaderTest.php b/src/Symfony/Component/Validator/Tests/Mapping/Loader/FilesLoaderTest.php index ae21625665c4..bc6aab8a34bf 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/Loader/FilesLoaderTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/Loader/FilesLoaderTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Mapping\Loader\LoaderInterface; +use Symfony\Component\Validator\Tests\Fixtures\FilesLoader; class FilesLoaderTest extends TestCase { @@ -34,7 +35,7 @@ public function testCallsActualFileLoaderForMetadata() public function getFilesLoader(LoaderInterface $loader) { - return $this->getMockForAbstractClass(\Symfony\Component\Validator\Tests\Fixtures\FilesLoader::class, [[ + return $this->getMockForAbstractClass(FilesLoader::class, [[ __DIR__.'/constraint-mapping.xml', __DIR__.'/constraint-mapping.yaml', __DIR__.'/constraint-mapping.test', @@ -44,6 +45,6 @@ public function getFilesLoader(LoaderInterface $loader) public function getFileLoader() { - return $this->getMockBuilder(LoaderInterface::class)->getMock(); + return $this->createMock(LoaderInterface::class); } } diff --git a/src/Symfony/Component/Validator/Tests/Mapping/Loader/LoaderChainTest.php b/src/Symfony/Component/Validator/Tests/Mapping/Loader/LoaderChainTest.php index c7ebaaa872f6..9ebe33ec1f59 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/Loader/LoaderChainTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/Loader/LoaderChainTest.php @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Mapping\Loader\LoaderChain; +use Symfony\Component\Validator\Mapping\Loader\LoaderInterface; class LoaderChainTest extends TestCase { @@ -21,12 +22,12 @@ public function testAllLoadersAreCalled() { $metadata = new ClassMetadata('\stdClass'); - $loader1 = $this->getMockBuilder(\Symfony\Component\Validator\Mapping\Loader\LoaderInterface::class)->getMock(); + $loader1 = $this->createMock(LoaderInterface::class); $loader1->expects($this->once()) ->method('loadClassMetadata') ->with($this->equalTo($metadata)); - $loader2 = $this->getMockBuilder(\Symfony\Component\Validator\Mapping\Loader\LoaderInterface::class)->getMock(); + $loader2 = $this->createMock(LoaderInterface::class); $loader2->expects($this->once()) ->method('loadClassMetadata') ->with($this->equalTo($metadata)); @@ -43,12 +44,12 @@ public function testReturnsTrueIfAnyLoaderReturnedTrue() { $metadata = new ClassMetadata('\stdClass'); - $loader1 = $this->getMockBuilder(\Symfony\Component\Validator\Mapping\Loader\LoaderInterface::class)->getMock(); + $loader1 = $this->createMock(LoaderInterface::class); $loader1->expects($this->any()) ->method('loadClassMetadata') ->willReturn(true); - $loader2 = $this->getMockBuilder(\Symfony\Component\Validator\Mapping\Loader\LoaderInterface::class)->getMock(); + $loader2 = $this->createMock(LoaderInterface::class); $loader2->expects($this->any()) ->method('loadClassMetadata') ->willReturn(false); @@ -65,12 +66,12 @@ public function testReturnsFalseIfNoLoaderReturnedTrue() { $metadata = new ClassMetadata('\stdClass'); - $loader1 = $this->getMockBuilder(\Symfony\Component\Validator\Mapping\Loader\LoaderInterface::class)->getMock(); + $loader1 = $this->createMock(LoaderInterface::class); $loader1->expects($this->any()) ->method('loadClassMetadata') ->willReturn(false); - $loader2 = $this->getMockBuilder(\Symfony\Component\Validator\Mapping\Loader\LoaderInterface::class)->getMock(); + $loader2 = $this->createMock(LoaderInterface::class); $loader2->expects($this->any()) ->method('loadClassMetadata') ->willReturn(false); diff --git a/src/Symfony/Component/Validator/Tests/Mapping/PropertyMetadataTest.php b/src/Symfony/Component/Validator/Tests/Mapping/PropertyMetadataTest.php index 6f926b9b0602..c581b3972045 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/PropertyMetadataTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/PropertyMetadataTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Validator\Tests\Mapping; use PHPUnit\Framework\TestCase; +use Symfony\Component\Validator\Exception\ValidatorException; use Symfony\Component\Validator\Mapping\PropertyMetadata; use Symfony\Component\Validator\Tests\Fixtures\Entity; use Symfony\Component\Validator\Tests\Fixtures\Entity_74; @@ -26,7 +27,7 @@ class PropertyMetadataTest extends TestCase public function testInvalidPropertyName() { - $this->expectException(\Symfony\Component\Validator\Exception\ValidatorException::class); + $this->expectException(ValidatorException::class); new PropertyMetadata(self::CLASSNAME, 'foobar'); } @@ -54,7 +55,7 @@ public function testGetPropertyValueFromRemovedProperty() $metadata = new PropertyMetadata(self::CLASSNAME, 'internal'); $metadata->name = 'test'; - $this->expectException(\Symfony\Component\Validator\Exception\ValidatorException::class); + $this->expectException(ValidatorException::class); $metadata->getPropertyValue($entity); } diff --git a/src/Symfony/Component/Validator/Tests/Validator/RecursiveValidatorTest.php b/src/Symfony/Component/Validator/Tests/Validator/RecursiveValidatorTest.php index e3bb8fe36638..0e55cca83461 100644 --- a/src/Symfony/Component/Validator/Tests/Validator/RecursiveValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Validator/RecursiveValidatorTest.php @@ -34,8 +34,12 @@ use Symfony\Component\Validator\ConstraintViolationInterface; use Symfony\Component\Validator\Context\ExecutionContextFactory; use Symfony\Component\Validator\Context\ExecutionContextInterface; +use Symfony\Component\Validator\Exception\ConstraintDefinitionException; +use Symfony\Component\Validator\Exception\NoSuchMetadataException; +use Symfony\Component\Validator\Exception\RuntimeException; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Mapping\Factory\MetadataFactoryInterface; +use Symfony\Component\Validator\ObjectInitializerInterface; use Symfony\Component\Validator\Tests\Constraints\Fixtures\ChildA; use Symfony\Component\Validator\Tests\Constraints\Fixtures\ChildB; use Symfony\Component\Validator\Tests\Fixtures\Entity; @@ -45,6 +49,7 @@ use Symfony\Component\Validator\Tests\Fixtures\FakeMetadataFactory; use Symfony\Component\Validator\Tests\Fixtures\GroupSequenceProviderEntity; use Symfony\Component\Validator\Tests\Fixtures\Reference; +use Symfony\Component\Validator\Validator\ContextualValidatorInterface; use Symfony\Component\Validator\Validator\LazyProperty; use Symfony\Component\Validator\Validator\RecursiveValidator; use Symfony\Component\Validator\Validator\ValidatorInterface; @@ -540,7 +545,7 @@ public function testsIgnoreNullReference() public function testFailOnScalarReferences() { - $this->expectException(\Symfony\Component\Validator\Exception\NoSuchMetadataException::class); + $this->expectException(NoSuchMetadataException::class); $entity = new Entity(); $entity->reference = 'string'; @@ -795,7 +800,7 @@ public function testDisableTraversableTraversal() public function testMetadataMustExistIfTraversalIsDisabled() { - $this->expectException(\Symfony\Component\Validator\Exception\NoSuchMetadataException::class); + $this->expectException(NoSuchMetadataException::class); $entity = new Entity(); $entity->reference = new \ArrayIterator(); @@ -1663,7 +1668,7 @@ public function testTraversalDisabledOnClass() public function testExpectTraversableIfTraversalEnabledOnClass() { - $this->expectException(\Symfony\Component\Validator\Exception\ConstraintDefinitionException::class); + $this->expectException(ConstraintDefinitionException::class); $entity = new Entity(); $this->metadata->addConstraint(new Traverse(true)); @@ -1819,7 +1824,7 @@ public function testNoDuplicateValidationIfPropertyConstraintInMultipleGroups() public function testValidateFailsIfNoConstraintsAndNoObjectOrArray() { - $this->expectException(\Symfony\Component\Validator\Exception\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->validate('Foobar'); } @@ -1850,8 +1855,8 @@ public function testInitializeObjectsOnFirstValidation() $entity->initialized = false; // prepare initializers that set "initialized" to true - $initializer1 = $this->getMockBuilder(\Symfony\Component\Validator\ObjectInitializerInterface::class)->getMock(); - $initializer2 = $this->getMockBuilder(\Symfony\Component\Validator\ObjectInitializerInterface::class)->getMock(); + $initializer1 = $this->createMock(ObjectInitializerInterface::class); + $initializer2 = $this->createMock(ObjectInitializerInterface::class); $initializer1->expects($this->once()) ->method('initialize') @@ -1993,7 +1998,7 @@ public function testEmptyGroupsArrayDoesNotTriggerDeprecation() $childB->name = 'fake'; $entity->childA = [$childA]; $entity->childB = [$childB]; - $validatorContext = $this->getMockBuilder(\Symfony\Component\Validator\Validator\ContextualValidatorInterface::class)->getMock(); + $validatorContext = $this->createMock(ContextualValidatorInterface::class); $validatorContext ->expects($this->once()) ->method('validate') @@ -2027,7 +2032,7 @@ public function testRelationBetweenChildAAndChildB() $entity->childA = [$childA]; $entity->childB = [$childB]; - $validatorContext = $this->getMockBuilder(\Symfony\Component\Validator\Validator\ContextualValidatorInterface::class)->getMock(); + $validatorContext = $this->createMock(ContextualValidatorInterface::class); $validatorContext ->expects($this->once()) ->method('validate') diff --git a/src/Symfony/Component/Validator/Tests/ValidatorBuilderTest.php b/src/Symfony/Component/Validator/Tests/ValidatorBuilderTest.php index ffd05c779fa8..6ef722938451 100644 --- a/src/Symfony/Component/Validator/Tests/ValidatorBuilderTest.php +++ b/src/Symfony/Component/Validator/Tests/ValidatorBuilderTest.php @@ -13,7 +13,12 @@ use PHPUnit\Framework\TestCase; use Psr\Cache\CacheItemPoolInterface; +use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Component\Validator\ConstraintValidatorFactoryInterface; +use Symfony\Component\Validator\Mapping\Cache\CacheInterface; +use Symfony\Component\Validator\ObjectInitializerInterface; use Symfony\Component\Validator\Util\LegacyTranslatorProxy; +use Symfony\Component\Validator\Validator\RecursiveValidator; use Symfony\Component\Validator\ValidatorBuilder; use Symfony\Component\Validator\ValidatorBuilderInterface; @@ -37,7 +42,7 @@ protected function tearDown(): void public function testAddObjectInitializer() { $this->assertSame($this->builder, $this->builder->addObjectInitializer( - $this->getMockBuilder(\Symfony\Component\Validator\ObjectInitializerInterface::class)->getMock() + $this->createMock(ObjectInitializerInterface::class) )); } @@ -98,27 +103,27 @@ public function testSetMappingCache() public function testSetMetadataCache() { $this->assertSame($this->builder, $this->builder->setMetadataCache( - $this->getMockBuilder(\Symfony\Component\Validator\Mapping\Cache\CacheInterface::class)->getMock()) + $this->createMock(CacheInterface::class)) ); } public function testSetConstraintValidatorFactory() { $this->assertSame($this->builder, $this->builder->setConstraintValidatorFactory( - $this->getMockBuilder(\Symfony\Component\Validator\ConstraintValidatorFactoryInterface::class)->getMock()) + $this->createMock(ConstraintValidatorFactoryInterface::class)) ); } public function testSetTranslator() { $this->assertSame($this->builder, $this->builder->setTranslator( - $this->getMockBuilder(\Symfony\Component\Translation\TranslatorInterface::class)->getMock()) + $this->createMock(TranslatorInterface::class)) ); } public function testLegacyTranslatorProxy() { - $proxy = $this->getMockBuilder(LegacyTranslatorProxy::class)->disableOriginalConstructor()->getMock(); + $proxy = $this->createMock(LegacyTranslatorProxy::class); $proxy->expects($this->once())->method('getTranslator'); $this->builder->setTranslator($proxy); @@ -131,6 +136,6 @@ public function testSetTranslationDomain() public function testGetValidator() { - $this->assertInstanceOf(\Symfony\Component\Validator\Validator\RecursiveValidator::class, $this->builder->getValidator()); + $this->assertInstanceOf(RecursiveValidator::class, $this->builder->getValidator()); } } diff --git a/src/Symfony/Component/VarDumper/Tests/Caster/PdoCasterTest.php b/src/Symfony/Component/VarDumper/Tests/Caster/PdoCasterTest.php index 21fecc996263..564c8a016667 100644 --- a/src/Symfony/Component/VarDumper/Tests/Caster/PdoCasterTest.php +++ b/src/Symfony/Component/VarDumper/Tests/Caster/PdoCasterTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\VarDumper\Tests\Caster; use PHPUnit\Framework\TestCase; +use Symfony\Component\VarDumper\Caster\ConstStub; +use Symfony\Component\VarDumper\Caster\EnumStub; use Symfony\Component\VarDumper\Caster\PdoCaster; use Symfony\Component\VarDumper\Cloner\Stub; use Symfony\Component\VarDumper\Test\VarDumperTestTrait; @@ -34,10 +36,10 @@ public function testCastPdo() $cast = PdoCaster::castPdo($pdo, [], new Stub(), false); - $this->assertInstanceOf(\Symfony\Component\VarDumper\Caster\EnumStub::class, $cast["\0~\0attributes"]); + $this->assertInstanceOf(EnumStub::class, $cast["\0~\0attributes"]); $attr = $cast["\0~\0attributes"] = $cast["\0~\0attributes"]->value; - $this->assertInstanceOf(\Symfony\Component\VarDumper\Caster\ConstStub::class, $attr['CASE']); + $this->assertInstanceOf(ConstStub::class, $attr['CASE']); $this->assertSame('NATURAL', $attr['CASE']->class); $this->assertSame('BOTH', $attr['DEFAULT_FETCH_MODE']->class); diff --git a/src/Symfony/Component/VarDumper/Tests/Dumper/ServerDumperTest.php b/src/Symfony/Component/VarDumper/Tests/Dumper/ServerDumperTest.php index 6999809fa97c..447d4856f732 100644 --- a/src/Symfony/Component/VarDumper/Tests/Dumper/ServerDumperTest.php +++ b/src/Symfony/Component/VarDumper/Tests/Dumper/ServerDumperTest.php @@ -25,7 +25,7 @@ class ServerDumperTest extends TestCase public function testDumpForwardsToWrappedDumperWhenServerIsUnavailable() { - $wrappedDumper = $this->getMockBuilder(DataDumperInterface::class)->getMock(); + $wrappedDumper = $this->createMock(DataDumperInterface::class); $dumper = new ServerDumper(self::VAR_DUMPER_SERVER, $wrappedDumper); @@ -39,7 +39,7 @@ public function testDumpForwardsToWrappedDumperWhenServerIsUnavailable() public function testDump() { - $wrappedDumper = $this->getMockBuilder(DataDumperInterface::class)->getMock(); + $wrappedDumper = $this->createMock(DataDumperInterface::class); $wrappedDumper->expects($this->never())->method('dump'); // test wrapped dumper is not used $cloner = new VarCloner(); diff --git a/src/Symfony/Component/VarExporter/Tests/InstantiatorTest.php b/src/Symfony/Component/VarExporter/Tests/InstantiatorTest.php index a5ce64a5b0a2..ab225a6f5513 100644 --- a/src/Symfony/Component/VarExporter/Tests/InstantiatorTest.php +++ b/src/Symfony/Component/VarExporter/Tests/InstantiatorTest.php @@ -12,13 +12,15 @@ namespace Symfony\Component\VarExporter\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\VarExporter\Exception\ClassNotFoundException; +use Symfony\Component\VarExporter\Exception\NotInstantiableTypeException; use Symfony\Component\VarExporter\Instantiator; class InstantiatorTest extends TestCase { public function testNotFoundClass() { - $this->expectException(\Symfony\Component\VarExporter\Exception\ClassNotFoundException::class); + $this->expectException(ClassNotFoundException::class); $this->expectExceptionMessage('Class "SomeNotExistingClass" not found.'); Instantiator::instantiate('SomeNotExistingClass'); } @@ -28,7 +30,7 @@ public function testNotFoundClass() */ public function testFailingInstantiation(string $class) { - $this->expectException(\Symfony\Component\VarExporter\Exception\NotInstantiableTypeException::class); + $this->expectException(NotInstantiableTypeException::class); $this->expectExceptionMessageMatches('/Type ".*" is not instantiable\./'); Instantiator::instantiate($class); } diff --git a/src/Symfony/Component/VarExporter/Tests/VarExporterTest.php b/src/Symfony/Component/VarExporter/Tests/VarExporterTest.php index 91480286674f..305abd1b7729 100644 --- a/src/Symfony/Component/VarExporter/Tests/VarExporterTest.php +++ b/src/Symfony/Component/VarExporter/Tests/VarExporterTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\VarDumper\Test\VarDumperTestTrait; +use Symfony\Component\VarExporter\Exception\ClassNotFoundException; +use Symfony\Component\VarExporter\Exception\NotInstantiableTypeException; use Symfony\Component\VarExporter\Internal\Registry; use Symfony\Component\VarExporter\VarExporter; @@ -22,7 +24,7 @@ class VarExporterTest extends TestCase public function testPhpIncompleteClassesAreForbidden() { - $this->expectException(\Symfony\Component\VarExporter\Exception\ClassNotFoundException::class); + $this->expectException(ClassNotFoundException::class); $this->expectExceptionMessage('Class "SomeNotExistingClass" not found.'); $unserializeCallback = ini_set('unserialize_callback_func', 'var_dump'); try { @@ -37,7 +39,7 @@ public function testPhpIncompleteClassesAreForbidden() */ public function testFailingSerialization($value) { - $this->expectException(\Symfony\Component\VarExporter\Exception\NotInstantiableTypeException::class); + $this->expectException(NotInstantiableTypeException::class); $this->expectExceptionMessageMatches('/Type ".*" is not instantiable\./'); $expectedDump = $this->getDump($value); try { diff --git a/src/Symfony/Component/Workflow/Tests/DefinitionTest.php b/src/Symfony/Component/Workflow/Tests/DefinitionTest.php index da20a2b3ac3d..ed6e7d38ba8d 100644 --- a/src/Symfony/Component/Workflow/Tests/DefinitionTest.php +++ b/src/Symfony/Component/Workflow/Tests/DefinitionTest.php @@ -4,6 +4,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Workflow\Definition; +use Symfony\Component\Workflow\Exception\LogicException; use Symfony\Component\Workflow\Transition; class DefinitionTest extends TestCase @@ -36,7 +37,7 @@ public function testSetInitialPlaces() public function testSetInitialPlaceAndPlaceIsNotDefined() { - $this->expectException(\Symfony\Component\Workflow\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Place "d" cannot be the initial place as it does not exist.'); new Definition([], [], 'd'); } @@ -54,7 +55,7 @@ public function testAddTransition() public function testAddTransitionAndFromPlaceIsNotDefined() { - $this->expectException(\Symfony\Component\Workflow\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Place "c" referenced in transition "name" does not exist.'); $places = range('a', 'b'); @@ -63,7 +64,7 @@ public function testAddTransitionAndFromPlaceIsNotDefined() public function testAddTransitionAndToPlaceIsNotDefined() { - $this->expectException(\Symfony\Component\Workflow\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Place "c" referenced in transition "name" does not exist.'); $places = range('a', 'b'); diff --git a/src/Symfony/Component/Workflow/Tests/EventListener/GuardListenerTest.php b/src/Symfony/Component/Workflow/Tests/EventListener/GuardListenerTest.php index 713cd45ca8ac..4d6741a2ea1c 100644 --- a/src/Symfony/Component/Workflow/Tests/EventListener/GuardListenerTest.php +++ b/src/Symfony/Component/Workflow/Tests/EventListener/GuardListenerTest.php @@ -39,11 +39,11 @@ protected function setUp(): void ]; $expressionLanguage = new ExpressionLanguage(); $token = new UsernamePasswordToken('username', 'credentials', 'provider', ['ROLE_USER']); - $tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock(); + $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage->expects($this->any())->method('getToken')->willReturn($token); - $this->authenticationChecker = $this->getMockBuilder(AuthorizationCheckerInterface::class)->getMock(); - $trustResolver = $this->getMockBuilder(AuthenticationTrustResolverInterface::class)->getMock(); - $this->validator = $this->getMockBuilder(ValidatorInterface::class)->getMock(); + $this->authenticationChecker = $this->createMock(AuthorizationCheckerInterface::class); + $trustResolver = $this->createMock(AuthenticationTrustResolverInterface::class); + $this->validator = $this->createMock(ValidatorInterface::class); $roleHierarchy = new RoleHierarchy([]); $this->listener = new GuardListener($this->configuration, $expressionLanguage, $tokenStorage, $this->authenticationChecker, $trustResolver, $roleHierarchy, $this->validator); } @@ -138,7 +138,7 @@ private function createEvent(Transition $transition = null) $subject = new Subject(); $transition = $transition ?: new Transition('name', 'from', 'to'); - $workflow = $this->getMockBuilder(WorkflowInterface::class)->getMock(); + $workflow = $this->createMock(WorkflowInterface::class); return new GuardEvent($subject, new Marking($subject->getMarking() ?? []), $transition, $workflow); } diff --git a/src/Symfony/Component/Workflow/Tests/Metadata/InMemoryMetadataStoreTest.php b/src/Symfony/Component/Workflow/Tests/Metadata/InMemoryMetadataStoreTest.php index 6a62c7bfed59..b834a60653f1 100644 --- a/src/Symfony/Component/Workflow/Tests/Metadata/InMemoryMetadataStoreTest.php +++ b/src/Symfony/Component/Workflow/Tests/Metadata/InMemoryMetadataStoreTest.php @@ -3,6 +3,7 @@ namespace Symfony\Component\Workflow\Tests\Metadata; use PHPUnit\Framework\TestCase; +use Symfony\Component\Workflow\Exception\InvalidArgumentException; use Symfony\Component\Workflow\Metadata\InMemoryMetadataStore; use Symfony\Component\Workflow\Transition; @@ -77,7 +78,7 @@ public function testGetMetadata() public function testGetMetadataWithUnknownType() { - $this->expectException(\Symfony\Component\Workflow\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Could not find a MetadataBag for the subject of type "boolean".'); $this->store->getMetadata('title', true); } diff --git a/src/Symfony/Component/Workflow/Tests/RegistryTest.php b/src/Symfony/Component/Workflow/Tests/RegistryTest.php index 26991dd182d5..3ad778080e1a 100644 --- a/src/Symfony/Component/Workflow/Tests/RegistryTest.php +++ b/src/Symfony/Component/Workflow/Tests/RegistryTest.php @@ -4,6 +4,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Workflow\Definition; +use Symfony\Component\Workflow\Exception\InvalidArgumentException; use Symfony\Component\Workflow\MarkingStore\MarkingStoreInterface; use Symfony\Component\Workflow\Registry; use Symfony\Component\Workflow\SupportStrategy\SupportStrategyInterface; @@ -19,9 +20,9 @@ protected function setUp(): void { $this->registry = new Registry(); - $this->registry->addWorkflow(new Workflow(new Definition([], []), $this->getMockBuilder(MarkingStoreInterface::class)->getMock(), $this->getMockBuilder(EventDispatcherInterface::class)->getMock(), 'workflow1'), $this->createWorkflowSupportStrategy(Subject1::class)); - $this->registry->addWorkflow(new Workflow(new Definition([], []), $this->getMockBuilder(MarkingStoreInterface::class)->getMock(), $this->getMockBuilder(EventDispatcherInterface::class)->getMock(), 'workflow2'), $this->createWorkflowSupportStrategy(Subject2::class)); - $this->registry->addWorkflow(new Workflow(new Definition([], []), $this->getMockBuilder(MarkingStoreInterface::class)->getMock(), $this->getMockBuilder(EventDispatcherInterface::class)->getMock(), 'workflow3'), $this->createWorkflowSupportStrategy(Subject2::class)); + $this->registry->addWorkflow(new Workflow(new Definition([], []), $this->createMock(MarkingStoreInterface::class), $this->createMock(EventDispatcherInterface::class), 'workflow1'), $this->createWorkflowSupportStrategy(Subject1::class)); + $this->registry->addWorkflow(new Workflow(new Definition([], []), $this->createMock(MarkingStoreInterface::class), $this->createMock(EventDispatcherInterface::class), 'workflow2'), $this->createWorkflowSupportStrategy(Subject2::class)); + $this->registry->addWorkflow(new Workflow(new Definition([], []), $this->createMock(MarkingStoreInterface::class), $this->createMock(EventDispatcherInterface::class), 'workflow3'), $this->createWorkflowSupportStrategy(Subject2::class)); } protected function tearDown(): void @@ -37,7 +38,7 @@ public function testAddIsDeprecated() { $registry = new Registry(); - $registry->add($w = new Workflow(new Definition([], []), $this->getMockBuilder(MarkingStoreInterface::class)->getMock(), $this->getMockBuilder(EventDispatcherInterface::class)->getMock(), 'workflow1'), $this->createSupportStrategy(Subject1::class)); + $registry->add($w = new Workflow(new Definition([], []), $this->createMock(MarkingStoreInterface::class), $this->createMock(EventDispatcherInterface::class), 'workflow1'), $this->createSupportStrategy(Subject1::class)); $workflow = $registry->get(new Subject1()); $this->assertInstanceOf(Workflow::class, $workflow); @@ -61,7 +62,7 @@ public function testGetWithSuccess() public function testGetWithMultipleMatch() { - $this->expectException(\Symfony\Component\Workflow\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Too many workflows (workflow2, workflow3) match this subject (Symfony\Component\Workflow\Tests\Subject2); set a different name on each and use the second (name) argument of this method.'); $w1 = $this->registry->get(new Subject2()); $this->assertInstanceOf(Workflow::class, $w1); @@ -70,7 +71,7 @@ public function testGetWithMultipleMatch() public function testGetWithNoMatch() { - $this->expectException(\Symfony\Component\Workflow\Exception\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Unable to find a workflow for class "stdClass".'); $w1 = $this->registry->get(new \stdClass()); $this->assertInstanceOf(Workflow::class, $w1); @@ -109,7 +110,7 @@ public function testAllWithNoMatch() */ private function createSupportStrategy($supportedClassName) { - $strategy = $this->getMockBuilder(SupportStrategyInterface::class)->getMock(); + $strategy = $this->createMock(SupportStrategyInterface::class); $strategy->expects($this->any())->method('supports') ->willReturnCallback(function ($workflow, $subject) use ($supportedClassName) { return $subject instanceof $supportedClassName; @@ -123,7 +124,7 @@ private function createSupportStrategy($supportedClassName) */ private function createWorkflowSupportStrategy($supportedClassName) { - $strategy = $this->getMockBuilder(WorkflowSupportStrategyInterface::class)->getMock(); + $strategy = $this->createMock(WorkflowSupportStrategyInterface::class); $strategy->expects($this->any())->method('supports') ->willReturnCallback(function ($workflow, $subject) use ($supportedClassName) { return $subject instanceof $supportedClassName; diff --git a/src/Symfony/Component/Workflow/Tests/SupportStrategy/ClassInstanceSupportStrategyTest.php b/src/Symfony/Component/Workflow/Tests/SupportStrategy/ClassInstanceSupportStrategyTest.php index e79a8a1f3f31..59238e792187 100644 --- a/src/Symfony/Component/Workflow/Tests/SupportStrategy/ClassInstanceSupportStrategyTest.php +++ b/src/Symfony/Component/Workflow/Tests/SupportStrategy/ClassInstanceSupportStrategyTest.php @@ -30,8 +30,6 @@ public function testSupportsIfNotClassInstance() private function createWorkflow() { - return $this->getMockBuilder(Workflow::class) - ->disableOriginalConstructor() - ->getMock(); + return $this->createMock(Workflow::class); } } diff --git a/src/Symfony/Component/Workflow/Tests/Validator/StateMachineValidatorTest.php b/src/Symfony/Component/Workflow/Tests/Validator/StateMachineValidatorTest.php index b929a8ca4217..357e5443952d 100644 --- a/src/Symfony/Component/Workflow/Tests/Validator/StateMachineValidatorTest.php +++ b/src/Symfony/Component/Workflow/Tests/Validator/StateMachineValidatorTest.php @@ -4,6 +4,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Workflow\Definition; +use Symfony\Component\Workflow\Exception\InvalidDefinitionException; use Symfony\Component\Workflow\Transition; use Symfony\Component\Workflow\Validator\StateMachineValidator; @@ -11,7 +12,7 @@ class StateMachineValidatorTest extends TestCase { public function testWithMultipleTransitionWithSameNameShareInput() { - $this->expectException(\Symfony\Component\Workflow\Exception\InvalidDefinitionException::class); + $this->expectException(InvalidDefinitionException::class); $this->expectExceptionMessage('A transition from a place/state must have an unique name.'); $places = ['a', 'b', 'c']; $transitions[] = new Transition('t1', 'a', 'b'); @@ -35,7 +36,7 @@ public function testWithMultipleTransitionWithSameNameShareInput() public function testWithMultipleTos() { - $this->expectException(\Symfony\Component\Workflow\Exception\InvalidDefinitionException::class); + $this->expectException(InvalidDefinitionException::class); $this->expectExceptionMessage('A transition in StateMachine can only have one output.'); $places = ['a', 'b', 'c']; $transitions[] = new Transition('t1', 'a', ['b', 'c']); @@ -58,7 +59,7 @@ public function testWithMultipleTos() public function testWithMultipleFroms() { - $this->expectException(\Symfony\Component\Workflow\Exception\InvalidDefinitionException::class); + $this->expectException(InvalidDefinitionException::class); $this->expectExceptionMessage('A transition in StateMachine can only have one input.'); $places = ['a', 'b', 'c']; $transitions[] = new Transition('t1', ['a', 'b'], 'c'); @@ -106,7 +107,7 @@ public function testValid() public function testWithTooManyInitialPlaces() { - $this->expectException(\Symfony\Component\Workflow\Exception\InvalidDefinitionException::class); + $this->expectException(InvalidDefinitionException::class); $this->expectExceptionMessage('The state machine "foo" can not store many places. But the definition has 2 initial places. Only one is supported.'); $places = range('a', 'c'); $transitions = []; diff --git a/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php b/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php index 12b90262f587..eda2d4e88668 100644 --- a/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php +++ b/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php @@ -4,6 +4,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Workflow\Definition; +use Symfony\Component\Workflow\Exception\InvalidDefinitionException; use Symfony\Component\Workflow\Tests\WorkflowBuilderTrait; use Symfony\Component\Workflow\Transition; use Symfony\Component\Workflow\Validator\WorkflowValidator; @@ -14,7 +15,7 @@ class WorkflowValidatorTest extends TestCase public function testSinglePlaceWorkflowValidatorAndComplexWorkflow() { - $this->expectException(\Symfony\Component\Workflow\Exception\InvalidDefinitionException::class); + $this->expectException(InvalidDefinitionException::class); $this->expectExceptionMessage('The marking store of workflow "foo" can not store many places.'); $definition = $this->createComplexWorkflowDefinition(); @@ -33,7 +34,7 @@ public function testSinglePlaceWorkflowValidatorAndSimpleWorkflow() public function testWorkflowWithInvalidNames() { - $this->expectException(\Symfony\Component\Workflow\Exception\InvalidDefinitionException::class); + $this->expectException(InvalidDefinitionException::class); $this->expectExceptionMessage('All transitions for a place must have an unique name. Multiple transitions named "t1" where found for place "a" in workflow "foo".'); $places = range('a', 'c'); @@ -49,7 +50,7 @@ public function testWorkflowWithInvalidNames() public function testWithTooManyInitialPlaces() { - $this->expectException(\Symfony\Component\Workflow\Exception\InvalidDefinitionException::class); + $this->expectException(InvalidDefinitionException::class); $this->expectExceptionMessage('The marking store of workflow "foo" can not store many places. But the definition has 2 initial places. Only one is supported.'); $places = range('a', 'c'); $transitions = []; diff --git a/src/Symfony/Component/Workflow/Tests/WorkflowTest.php b/src/Symfony/Component/Workflow/Tests/WorkflowTest.php index 14e30bebc744..7d688d0d7f63 100644 --- a/src/Symfony/Component/Workflow/Tests/WorkflowTest.php +++ b/src/Symfony/Component/Workflow/Tests/WorkflowTest.php @@ -8,7 +8,9 @@ use Symfony\Component\Workflow\Event\Event; use Symfony\Component\Workflow\Event\GuardEvent; use Symfony\Component\Workflow\Event\TransitionEvent; +use Symfony\Component\Workflow\Exception\LogicException; use Symfony\Component\Workflow\Exception\NotEnabledTransitionException; +use Symfony\Component\Workflow\Exception\UndefinedTransitionException; use Symfony\Component\Workflow\Marking; use Symfony\Component\Workflow\MarkingStore\MarkingStoreInterface; use Symfony\Component\Workflow\MarkingStore\MethodMarkingStore; @@ -22,17 +24,17 @@ class WorkflowTest extends TestCase public function testGetMarkingWithInvalidStoreReturn() { - $this->expectException(\Symfony\Component\Workflow\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('The value returned by the MarkingStore is not an instance of "Symfony\Component\Workflow\Marking" for workflow "unnamed".'); $subject = new Subject(); - $workflow = new Workflow(new Definition([], []), $this->getMockBuilder(MarkingStoreInterface::class)->getMock()); + $workflow = new Workflow(new Definition([], []), $this->createMock(MarkingStoreInterface::class)); $workflow->getMarking($subject); } public function testGetMarkingWithEmptyDefinition() { - $this->expectException(\Symfony\Component\Workflow\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('The Marking is empty and there is no initial place for workflow "unnamed".'); $subject = new Subject(); $workflow = new Workflow(new Definition([], []), new MethodMarkingStore()); @@ -42,7 +44,7 @@ public function testGetMarkingWithEmptyDefinition() public function testGetMarkingWithImpossiblePlace() { - $this->expectException(\Symfony\Component\Workflow\Exception\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Place "nope" is not valid for workflow "unnamed".'); $subject = new Subject(); $subject->setMarking(['nope' => 1]); @@ -169,7 +171,7 @@ public function testCanWithSameNameTransition() public function testBuildTransitionBlockerListReturnsUndefinedTransition() { - $this->expectException(\Symfony\Component\Workflow\Exception\UndefinedTransitionException::class); + $this->expectException(UndefinedTransitionException::class); $this->expectExceptionMessage('Transition "404 Not Found" is not defined for workflow "unnamed".'); $definition = $this->createSimpleWorkflowDefinition(); $subject = new Subject(); @@ -249,7 +251,7 @@ public function testBuildTransitionBlockerListReturnsReasonsProvidedInGuards() public function testApplyWithNotExisingTransition() { - $this->expectException(\Symfony\Component\Workflow\Exception\UndefinedTransitionException::class); + $this->expectException(UndefinedTransitionException::class); $this->expectExceptionMessage('Transition "404 Not Found" is not defined for workflow "unnamed".'); $definition = $this->createComplexWorkflowDefinition(); $subject = new Subject(); diff --git a/src/Symfony/Component/Yaml/Tests/DumperTest.php b/src/Symfony/Component/Yaml/Tests/DumperTest.php index 7f3e245f308e..6329aec86ccf 100644 --- a/src/Symfony/Component/Yaml/Tests/DumperTest.php +++ b/src/Symfony/Component/Yaml/Tests/DumperTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Yaml\Dumper; +use Symfony\Component\Yaml\Exception\DumpException; use Symfony\Component\Yaml\Parser; use Symfony\Component\Yaml\Tag\TaggedValue; use Symfony\Component\Yaml\Yaml; @@ -194,7 +195,7 @@ public function testObjectSupportDisabledButNoExceptions() public function testObjectSupportDisabledWithExceptions() { - $this->expectException(\Symfony\Component\Yaml\Exception\DumpException::class); + $this->expectException(DumpException::class); $this->dumper->dump(['foo' => new A(), 'bar' => 1], 0, 0, Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE); } diff --git a/src/Symfony/Contracts/Tests/Cache/CacheTraitTest.php b/src/Symfony/Contracts/Tests/Cache/CacheTraitTest.php index f1300a6f9d1c..6572a458381e 100644 --- a/src/Symfony/Contracts/Tests/Cache/CacheTraitTest.php +++ b/src/Symfony/Contracts/Tests/Cache/CacheTraitTest.php @@ -23,7 +23,7 @@ class CacheTraitTest extends TestCase { public function testSave() { - $item = $this->getMockBuilder(CacheItemInterface::class)->getMock(); + $item = $this->createMock(CacheItemInterface::class); $item->method('set') ->willReturn($item); $item->method('isHit') @@ -52,7 +52,7 @@ public function testSave() public function testNoCallbackCallOnHit() { - $item = $this->getMockBuilder(CacheItemInterface::class)->getMock(); + $item = $this->createMock(CacheItemInterface::class); $item->method('isHit') ->willReturn(true); @@ -79,7 +79,7 @@ public function testNoCallbackCallOnHit() public function testRecomputeOnBetaInf() { - $item = $this->getMockBuilder(CacheItemInterface::class)->getMock(); + $item = $this->createMock(CacheItemInterface::class); $item->method('set') ->willReturn($item); $item->method('isHit')