diff --git a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.php b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.php index 6edfbbc3b5328..3a8c4bf147fda 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.php @@ -27,7 +27,6 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase public function testExceptionOnAbstractTaggedSubscriber() { - $this->expectException(\InvalidArgumentException::class); $container = $this->createBuilder(); $abstractDefinition = new Definition('stdClass'); @@ -36,12 +35,13 @@ public function testExceptionOnAbstractTaggedSubscriber() $container->setDefinition('a', $abstractDefinition); + $this->expectException(\InvalidArgumentException::class); + $this->process($container); } public function testExceptionOnAbstractTaggedListener() { - $this->expectException(\InvalidArgumentException::class); $container = $this->createBuilder(); $abstractDefinition = new Definition('stdClass'); @@ -50,6 +50,8 @@ public function testExceptionOnAbstractTaggedListener() $container->setDefinition('a', $abstractDefinition); + $this->expectException(\InvalidArgumentException::class); + $this->process($container); } diff --git a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterMappingsPassTest.php b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterMappingsPassTest.php index fecc532a0b609..2dfffc36fdbbc 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterMappingsPassTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterMappingsPassTest.php @@ -20,9 +20,11 @@ class RegisterMappingsPassTest extends TestCase { public function testNoDriverParmeterException() { + $container = $this->createBuilder(); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Could not find the manager name parameter in the container. Tried the following parameter names: "manager.param.one", "manager.param.two"'); - $container = $this->createBuilder(); + $this->process($container, [ 'manager.param.one', 'manager.param.two', diff --git a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php index f487cfb0e9245..9a61feaca92a8 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php @@ -58,7 +58,6 @@ protected function setUp(): void public function testFixManagersAutoMappingsWithTwoAutomappings() { - $this->expectException(\LogicException::class); $emConfigs = [ 'em1' => [ 'auto_mapping' => true, @@ -76,6 +75,8 @@ public function testFixManagersAutoMappingsWithTwoAutomappings() $reflection = new \ReflectionClass($this->extension); $method = $reflection->getMethod('fixManagersAutoMappings'); + $this->expectException(\LogicException::class); + $method->invoke($this->extension, $emConfigs, $bundles); } @@ -255,8 +256,6 @@ public function testServiceCacheDriver() public function testUnrecognizedCacheDriverException() { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('"unrecognized_type" is an unrecognized Doctrine cache driver.'); $cacheName = 'metadata_cache'; $container = $this->createContainer(); $objectManager = [ @@ -266,6 +265,9 @@ public function testUnrecognizedCacheDriverException() ], ]; + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('"unrecognized_type" is an unrecognized Doctrine cache driver.'); + $this->invokeLoadCacheDriver($objectManager, $container, $cacheName); } diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php index 9e6355670fc47..49796d406489a 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php @@ -152,9 +152,6 @@ public function testLoadValuesForChoicesDoesNotLoadIfEmptyChoices() public function testLoadValuesForChoicesDoesNotLoadIfSingleIntId() { - $this->expectException(LogicException::class); - $this->expectExceptionMessage('Not defining the IdReader explicitly as a value callback when the query can be optimized is not supported.'); - $loader = new DoctrineChoiceLoader( $this->om, $this->class, @@ -169,7 +166,10 @@ public function testLoadValuesForChoicesDoesNotLoadIfSingleIntId() ->with($this->obj2) ->willReturn('2'); - $this->assertSame(['2'], $loader->loadValuesForChoices([$this->obj2])); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Not defining the IdReader explicitly as a value callback when the query can be optimized is not supported.'); + + $loader->loadValuesForChoices([$this->obj2]); } public function testLoadValuesForChoicesDoesNotLoadIfSingleIntIdAndValueGiven() @@ -253,9 +253,6 @@ public function testLoadChoicesForValuesDoesNotLoadIfEmptyValues() public function testLegacyLoadChoicesForValuesLoadsOnlyChoicesIfValueUseIdReader() { - $this->expectException(LogicException::class); - $this->expectExceptionMessage('Not defining the IdReader explicitly as a value callback when the query can be optimized is not supported.'); - $loader = new DoctrineChoiceLoader( $this->om, $this->class, @@ -263,8 +260,6 @@ public function testLegacyLoadChoicesForValuesLoadsOnlyChoicesIfValueUseIdReader $this->objectLoader ); - $choices = [$this->obj2, $this->obj3]; - $this->idReader->expects($this->any()) ->method('getIdField') ->willReturn('idField'); @@ -275,10 +270,10 @@ public function testLegacyLoadChoicesForValuesLoadsOnlyChoicesIfValueUseIdReader $this->objectLoader->expects($this->never()) ->method('getEntitiesByIds'); - $this->assertSame( - [4 => $this->obj3, 7 => $this->obj2], - $loader->loadChoicesForValues([4 => '3', 7 => '2']) - ); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Not defining the IdReader explicitly as a value callback when the query can be optimized is not supported.'); + + $loader->loadChoicesForValues([4 => '3', 7 => '2']); } public function testLoadChoicesForValuesLoadsOnlyChoicesIfValueUseIdReader() @@ -374,15 +369,15 @@ public function testLoadChoicesForValuesLoadsOnlyChoicesIfValueIsIdReader() public function testPassingIdReaderWithoutSingleIdEntity() { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The "$idReader" argument of "Symfony\\Bridge\\Doctrine\\Form\\ChoiceList\\DoctrineChoiceLoader::__construct" must be null when the query cannot be optimized because of composite id fields.'); - $idReader = $this->createMock(IdReader::class); $idReader->expects($this->once()) ->method('isSingleId') ->willReturn(false) ; + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The "$idReader" argument of "Symfony\\Bridge\\Doctrine\\Form\\ChoiceList\\DoctrineChoiceLoader::__construct" must be null when the query cannot be optimized because of composite id fields.'); + new DoctrineChoiceLoader($this->om, $this->class, $idReader, $this->objectLoader); } } diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php index c942d72c508e3..a3946c624f85d 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php @@ -218,7 +218,7 @@ public function testConfigureQueryBuilderWithNonQueryBuilderAndNonClosure() public function testConfigureQueryBuilderWithClosureReturningNonQueryBuilder() { $this->expectException(UnexpectedTypeException::class); - $field = $this->factory->createNamed('name', static::TESTED_TYPE, null, [ + $this->factory->createNamed('name', static::TESTED_TYPE, null, [ 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'query_builder' => fn () => new \stdClass(), diff --git a/src/Symfony/Bridge/Doctrine/Tests/Messenger/DoctrineTransactionMiddlewareTest.php b/src/Symfony/Bridge/Doctrine/Tests/Messenger/DoctrineTransactionMiddlewareTest.php index ed585550e39b6..f0eb0b22efcf4 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Messenger/DoctrineTransactionMiddlewareTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Messenger/DoctrineTransactionMiddlewareTest.php @@ -56,8 +56,6 @@ public function testMiddlewareWrapsInTransactionAndFlushes() public function testTransactionIsRolledBackOnException() { - $this->expectException(\RuntimeException::class); - $this->expectExceptionMessage('Thrown from next middleware.'); $this->connection->expects($this->once()) ->method('beginTransaction') ; @@ -65,6 +63,9 @@ public function testTransactionIsRolledBackOnException() ->method('rollBack') ; + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Thrown from next middleware.'); + $this->middleware->handle(new Envelope(new \stdClass()), $this->getThrowingStackMock()); } diff --git a/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php b/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php index 9275dc46bd11f..aadc837aa4e72 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php @@ -89,8 +89,6 @@ public function testLoadUserByIdentifierWithUserLoaderRepositoryAndWithoutProper public function testLoadUserByIdentifierWithNonUserLoaderRepositoryAndWithoutProperty() { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('You must either make the "Symfony\Bridge\Doctrine\Tests\Fixtures\User" entity Doctrine Repository ("Doctrine\ORM\EntityRepository") implement "Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface" or set the "property" option in the corresponding entity provider configuration.'); $em = DoctrineTestHelper::createTestEntityManager(); $this->createSchema($em); @@ -100,6 +98,10 @@ public function testLoadUserByIdentifierWithNonUserLoaderRepositoryAndWithoutPro $em->flush(); $provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User'); + + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('You must either make the "Symfony\Bridge\Doctrine\Tests\Fixtures\User" entity Doctrine Repository ("Doctrine\ORM\EntityRepository") implement "Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface" or set the "property" option in the corresponding entity provider configuration.'); + $provider->loadUserByIdentifier('user1'); } @@ -171,7 +173,6 @@ public function testLoadUserByIdentifierShouldLoadUserWhenProperInterfaceProvide public function testLoadUserByIdentifierShouldDeclineInvalidInterface() { - $this->expectException(\InvalidArgumentException::class); $repository = $this->createMock(ObjectRepository::class); $provider = new EntityUserProvider( @@ -179,6 +180,8 @@ public function testLoadUserByIdentifierShouldDeclineInvalidInterface() 'Symfony\Bridge\Doctrine\Tests\Fixtures\User' ); + $this->expectException(\InvalidArgumentException::class); + $provider->loadUserByIdentifier('name'); } diff --git a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php index c010add009fdf..5e29439368517 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php @@ -617,8 +617,6 @@ public function testValidateUniquenessWithArrayValue() public function testDedicatedEntityManagerNullObject() { - $this->expectException(ConstraintDefinitionException::class); - $this->expectExceptionMessage('Object manager "foo" does not exist.'); $constraint = new UniqueEntity([ 'message' => 'myMessage', 'fields' => ['name'], @@ -632,13 +630,14 @@ public function testDedicatedEntityManagerNullObject() $entity = new SingleIntIdEntity(1, null); + $this->expectException(ConstraintDefinitionException::class); + $this->expectExceptionMessage('Object manager "foo" does not exist.'); + $this->validator->validate($entity, $constraint); } public function testEntityManagerNullObject() { - $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', 'fields' => ['name'], @@ -652,6 +651,9 @@ public function testEntityManagerNullObject() $entity = new SingleIntIdEntity(1, null); + $this->expectException(ConstraintDefinitionException::class); + $this->expectExceptionMessage('Unable to find the object manager associated with an entity of class "Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity"'); + $this->validator->validate($entity, $constraint); } @@ -719,8 +721,6 @@ public function testValidateInheritanceUniqueness() public function testInvalidateRepositoryForInheritance() { - $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'], @@ -729,6 +729,10 @@ public function testInvalidateRepositoryForInheritance() ]); $entity = new Person(1, 'Foo'); + + $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".'); + $this->validator->validate($entity, $constraint); } diff --git a/src/Symfony/Bridge/PsrHttpMessage/Tests/Factory/HttpFoundationFactoryTest.php b/src/Symfony/Bridge/PsrHttpMessage/Tests/Factory/HttpFoundationFactoryTest.php index 1b7a4d1caed90..ed2b7e9d8e2bf 100644 --- a/src/Symfony/Bridge/PsrHttpMessage/Tests/Factory/HttpFoundationFactoryTest.php +++ b/src/Symfony/Bridge/PsrHttpMessage/Tests/Factory/HttpFoundationFactoryTest.php @@ -185,14 +185,14 @@ public function testCreateUploadedFile() public function testCreateUploadedFileWithError() { - $this->expectException(FileException::class); - $this->expectExceptionMessage('The file "e" could not be written on disk.'); - $uploadedFile = $this->createUploadedFile('Error.', \UPLOAD_ERR_CANT_WRITE, 'e', 'text/plain'); $symfonyUploadedFile = $this->callCreateUploadedFile($uploadedFile); $this->assertEquals(\UPLOAD_ERR_CANT_WRITE, $symfonyUploadedFile->getError()); + $this->expectException(FileException::class); + $this->expectExceptionMessage('The file "e" could not be written on disk.'); + $symfonyUploadedFile->move($this->tmpDir, 'shouldFail.txt'); } diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php index e7f58f4f48aee..5bce112d19d0c 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php @@ -30,9 +30,10 @@ class HttpKernelExtensionTest extends TestCase { public function testFragmentWithError() { - $this->expectException(\Twig\Error\RuntimeError::class); $renderer = $this->getFragmentHandler($this->throwException(new \Exception('foo'))); + $this->expectException(\Twig\Error\RuntimeError::class); + $this->renderTemplate($renderer); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php index 8c004d267b9eb..251d2fa6ad8f0 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php @@ -118,7 +118,6 @@ public function testDebugCustomDirectory() public function testDebugInvalidDirectory() { - $this->expectException(\InvalidArgumentException::class); $kernel = $this->createMock(KernelInterface::class); $kernel->expects($this->once()) ->method('getBundle') @@ -126,6 +125,9 @@ public function testDebugInvalidDirectory() ->willThrowException(new \InvalidArgumentException()); $tester = $this->createCommandTester([], [], $kernel); + + $this->expectException(\InvalidArgumentException::class); + $tester->execute(['locale' => 'en', 'bundle' => 'dir']); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/YamlLintCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/YamlLintCommandTest.php index 667c76a4a3659..08f4a75265abf 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/YamlLintCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/YamlLintCommandTest.php @@ -60,11 +60,12 @@ public function testLintIncorrectFile() public function testLintFileNotReadable() { - $this->expectException(\RuntimeException::class); $tester = $this->createCommandTester(); $filename = $this->createFile(''); unlink($filename); + $this->expectException(\RuntimeException::class); + $tester->execute(['filename' => $filename], ['decorated' => false]); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php index aa3e67919ecc8..f806c540b278b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php @@ -92,13 +92,14 @@ public function testGetParameter() public function testMissingParameterBag() { - $this->expectException(ServiceNotFoundException::class); - $this->expectExceptionMessage('TestAbstractController::getParameter()" method is missing a parameter bag'); $container = new Container(); $controller = $this->createController(); $controller->setContainer($container); + $this->expectException(ServiceNotFoundException::class); + $this->expectExceptionMessage('TestAbstractController::getParameter()" method is missing a parameter bag'); + $controller->getParameter('foo'); } @@ -146,12 +147,12 @@ public function testGetUserWithEmptyTokenStorage() public function testGetUserWithEmptyContainer() { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('The SecurityBundle is not registered in your application.'); - $controller = $this->createController(); $controller->setContainer(new Container()); + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('The SecurityBundle is not registered in your application.'); + $controller->getUser(); } @@ -327,10 +328,10 @@ public function testFileFromPathWithCustomizedFileName() public function testFileWhichDoesNotExist() { - $this->expectException(FileNotFoundException::class); - $controller = $this->createController(); + $this->expectException(FileNotFoundException::class); + $controller->file('some-file.txt', 'test.php'); } @@ -350,8 +351,6 @@ public function testIsGranted() public function testdenyAccessUnlessGranted() { - $this->expectException(AccessDeniedException::class); - $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class); $authorizationChecker->expects($this->once())->method('isGranted')->willReturn(false); @@ -361,6 +360,8 @@ public function testdenyAccessUnlessGranted() $controller = $this->createController(); $controller->setContainer($container); + $this->expectException(AccessDeniedException::class); + $controller->denyAccessUnlessGranted('foo'); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php index c0f5da11f6a3d..c972151d2c0b0 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php @@ -47,7 +47,7 @@ public function testNoTwigInvokeMethod() $controller = new TemplateController(); $this->expectException(\LogicException::class); - $this->expectExceptionMessage('You cannot use the TemplateController if the Twig Bundle is not available.'); + $this->expectExceptionMessage('You cannot use the TemplateController if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".'); $controller('mytemplate')->getContent(); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/ProfilerPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/ProfilerPassTest.php index eef047dfa8c29..46982578227ef 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/ProfilerPassTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/ProfilerPassTest.php @@ -34,13 +34,15 @@ class ProfilerPassTest extends TestCase */ public function testTemplateNoIdThrowsException() { - $this->expectException(\InvalidArgumentException::class); $builder = new ContainerBuilder(); $builder->register('profiler', 'ProfilerClass'); $builder->register('my_collector_service') ->addTag('data_collector', ['template' => 'foo']); $profilerPass = new ProfilerPass(); + + $this->expectException(\InvalidArgumentException::class); + $profilerPass->process($builder); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php index 4c3327847c3af..15016df363a33 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php @@ -58,49 +58,53 @@ public function testNoExeptionIfAllDependenciesArePresent() public function testExceptionIfTheTokenStorageServiceIsNotPresent() { - $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); $this->container->register('security.authentication.trust_resolver', AuthenticationTrustResolverInterface::class); $this->container->register('security.role_hierarchy', RoleHierarchy::class); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('The "security.token_storage" service is needed to be able to use the workflow guard listener.'); + $this->compilerPass->process($this->container); } public function testExceptionIfTheAuthorizationCheckerServiceIsNotPresent() { - $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); $this->container->register('security.authentication.trust_resolver', AuthenticationTrustResolverInterface::class); $this->container->register('security.role_hierarchy', RoleHierarchy::class); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('The "security.authorization_checker" service is needed to be able to use the workflow guard listener.'); + $this->compilerPass->process($this->container); } public function testExceptionIfTheAuthenticationTrustResolverServiceIsNotPresent() { - $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); $this->container->register('security.authorization_checker', AuthorizationCheckerInterface::class); $this->container->register('security.role_hierarchy', RoleHierarchy::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->compilerPass->process($this->container); } public function testExceptionIfTheRoleHierarchyServiceIsNotPresent() { - $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); $this->container->register('security.authorization_checker', AuthorizationCheckerInterface::class); $this->container->register('security.authentication.trust_resolver', AuthenticationTrustResolverInterface::class); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('The "security.role_hierarchy" service is needed to be able to use the workflow guard listener.'); + $this->compilerPass->process($this->container); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php index 287d0e7e448fd..ab08f47655a8b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php @@ -61,8 +61,10 @@ public function getTestValidSessionName() */ public function testInvalidSessionName($sessionName) { - $this->expectException(InvalidConfigurationException::class); $processor = new Processor(); + + $this->expectException(InvalidConfigurationException::class); + $processor->processConfiguration( new Configuration(true), [[ @@ -177,11 +179,12 @@ public static function provideValidAssetsPackageNameConfigurationTests(): array */ public function testInvalidAssetsConfiguration(array $assetConfig, $expectedMessage) { + $processor = new Processor(); + $configuration = new Configuration(true); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage($expectedMessage); - $processor = new Processor(); - $configuration = new Configuration(true); $processor->processConfiguration($configuration, [ [ 'http_method_override' => false, diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTestCase.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTestCase.php index 6e3db3a0f1dc0..70e0132926b28 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTestCase.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTestCase.php @@ -634,9 +634,11 @@ public function testRouter() public function testRouterRequiresResourceOption() { - $this->expectException(InvalidConfigurationException::class); $container = $this->createContainer(); $loader = new FrameworkExtension(); + + $this->expectException(InvalidConfigurationException::class); + $loader->load([['http_method_override' => false, 'handle_all_throwables' => true, 'php_errors' => ['log' => true], 'router' => true]], $container); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/RouterDebugCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/RouterDebugCommandTest.php index 9093469176675..61407880457ce 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/RouterDebugCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/RouterDebugCommandTest.php @@ -81,9 +81,11 @@ public function testSearchMultipleRoutesWithoutInteraction() public function testSearchWithThrow() { + $tester = $this->createCommandTester(); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('The route "gerard" does not exist.'); - $tester = $this->createCommandTester(); + $tester->execute(['name' => 'gerard'], ['interactive' => true]); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RouterTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RouterTest.php index d89a09489baa3..3e185b54c5553 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RouterTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RouterTest.php @@ -299,25 +299,29 @@ public function testPatternPlaceholdersWithSfContainer() public function testEnvPlaceholders() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Using "%env(FOO)%" is not allowed in routing configuration.'); $routes = new RouteCollection(); $routes->add('foo', new Route('/%env(FOO)%')); $router = new Router($this->getPsr11ServiceContainer($routes), 'foo', [], null, $this->getParameterBag()); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Using "%env(FOO)%" is not allowed in routing configuration.'); + $router->getRouteCollection(); } public function testEnvPlaceholdersWithSfContainer() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Using "%env(FOO)%" is not allowed in routing configuration.'); $routes = new RouteCollection(); $routes->add('foo', new Route('/%env(FOO)%')); $router = new Router($this->getServiceContainer($routes), 'foo'); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Using "%env(FOO)%" is not allowed in routing configuration.'); + $router->getRouteCollection(); } @@ -381,8 +385,6 @@ public function testHostPlaceholdersWithSfContainer() public function testExceptionOnNonExistentParameterWithSfContainer() { - $this->expectException(ParameterNotFoundException::class); - $this->expectExceptionMessage('You have requested a non-existent parameter "nope".'); $routes = new RouteCollection(); $routes->add('foo', new Route('/%nope%')); @@ -390,13 +392,15 @@ public function testExceptionOnNonExistentParameterWithSfContainer() $sc = $this->getServiceContainer($routes); $router = new Router($sc, 'foo'); + + $this->expectException(ParameterNotFoundException::class); + $this->expectExceptionMessage('You have requested a non-existent parameter "nope".'); + $router->getRouteCollection()->get('foo'); } public function testExceptionOnNonStringParameter() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('The container parameter "object", used in the route configuration value "/%object%", must be a string or numeric, but it is of type "stdClass".'); $routes = new RouteCollection(); $routes->add('foo', new Route('/%object%')); @@ -405,6 +409,10 @@ public function testExceptionOnNonStringParameter() $parameters = $this->getParameterBag(['object' => new \stdClass()]); $router = new Router($sc, 'foo', [], null, $parameters); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The container parameter "object", used in the route configuration value "/%object%", must be a string or numeric, but it is of type "stdClass".'); + $router->getRouteCollection()->get('foo'); } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSecurityVotersPassTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSecurityVotersPassTest.php index b4c2009584f5e..ca18730716ba4 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSecurityVotersPassTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSecurityVotersPassTest.php @@ -24,8 +24,6 @@ class AddSecurityVotersPassTest extends TestCase { public function testNoVoters() { - $this->expectException(LogicException::class); - $this->expectExceptionMessage('No security voters found. You need to tag at least one with "security.voter".'); $container = new ContainerBuilder(); $container ->register('security.access.decision_manager', AccessDecisionManager::class) @@ -33,6 +31,10 @@ public function testNoVoters() ; $compilerPass = new AddSecurityVotersPass(); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('No security voters found. You need to tag at least one with "security.voter".'); + $compilerPass->process($container); } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/MainConfigurationTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/MainConfigurationTest.php index 5a813010653d3..52a392fe870f7 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/MainConfigurationTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/MainConfigurationTest.php @@ -36,7 +36,6 @@ class MainConfigurationTest extends TestCase public function testNoConfigForProvider() { - $this->expectException(InvalidConfigurationException::class); $config = [ 'providers' => [ 'stub' => [], @@ -45,12 +44,14 @@ public function testNoConfigForProvider() $processor = new Processor(); $configuration = new MainConfiguration([], []); + + $this->expectException(InvalidConfigurationException::class); + $processor->processConfiguration($configuration, [$config]); } public function testManyConfigForProvider() { - $this->expectException(InvalidConfigurationException::class); $config = [ 'providers' => [ 'stub' => [ @@ -62,6 +63,9 @@ public function testManyConfigForProvider() $processor = new Processor(); $configuration = new MainConfiguration([], []); + + $this->expectException(InvalidConfigurationException::class); + $processor->processConfiguration($configuration, [$config]); } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/AccessTokenFactoryTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/AccessTokenFactoryTest.php index e733c7efc644b..e1f55817eee68 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/AccessTokenFactoryTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/AccessTokenFactoryTest.php @@ -145,9 +145,6 @@ public static function getOidcUserInfoConfiguration(): iterable public function testMultipleTokenHandlersSet() { - $this->expectException(InvalidConfigurationException::class); - $this->expectExceptionMessage('You cannot configure multiple token handlers.'); - $config = [ 'token_handler' => [ 'id' => 'in_memory_token_handler_service_id', @@ -156,6 +153,10 @@ public function testMultipleTokenHandlersSet() ]; $factory = new AccessTokenFactory($this->createTokenHandlerFactories()); + + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('You cannot configure multiple token handlers.'); + $this->processConfig($config, $factory); } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php index 5db604b1c5a5d..03b0b0d045f14 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php @@ -45,8 +45,6 @@ class SecurityExtensionTest extends TestCase public function testInvalidCheckPath() { - $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(); $container->loadFromExtension('security', [ @@ -64,13 +62,14 @@ public function testInvalidCheckPath() ], ]); + $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->compile(); } public function testFirewallWithInvalidUserProvider() { - $this->expectException(InvalidConfigurationException::class); - $this->expectExceptionMessage('Unable to create definition for "security.user.provider.concrete.my_foo" user provider'); $container = $this->getRawContainer(); $extension = $container->getExtension('security'); @@ -89,6 +88,9 @@ public function testFirewallWithInvalidUserProvider() ], ]); + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('Unable to create definition for "security.user.provider.concrete.my_foo" user provider'); + $container->compile(); } @@ -161,8 +163,6 @@ public function testPerListenerProvider() public function testMissingProviderForListener() { - $this->expectException(InvalidConfigurationException::class); - $this->expectExceptionMessage('Not configuring explicitly the provider for the "http_basic" authenticator on "ambiguous" firewall is ambiguous as there is more than one registered provider.'); $container = $this->getRawContainer(); $container->loadFromExtension('security', [ 'providers' => [ @@ -178,6 +178,9 @@ public function testMissingProviderForListener() ], ]); + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('Not configuring explicitly the provider for the "http_basic" authenticator on "ambiguous" firewall is ambiguous as there is more than one registered provider.'); + $container->compile(); } @@ -712,9 +715,6 @@ public static function provideEntryPointFirewalls(): iterable */ public function testEntryPointRequired(array $firewall, string $messageRegex) { - $this->expectException(InvalidConfigurationException::class); - $this->expectExceptionMessageMatches($messageRegex); - $container = $this->getRawContainer(); $container->loadFromExtension('security', [ 'providers' => [ @@ -726,6 +726,9 @@ public function testEntryPointRequired(array $firewall, string $messageRegex) ], ]); + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessageMatches($messageRegex); + $container->compile(); } diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php index 755512f9e14bc..6b6b6cf9a8a5f 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php @@ -34,13 +34,14 @@ class ProfilerControllerTest extends WebTestCase { public function testHomeActionWithProfilerDisabled() { - $this->expectException(NotFoundHttpException::class); - $this->expectExceptionMessage('The profiler must be enabled.'); - $urlGenerator = $this->createMock(UrlGeneratorInterface::class); $twig = $this->createMock(Environment::class); $controller = new ProfilerController($urlGenerator, null, $twig, []); + + $this->expectException(NotFoundHttpException::class); + $this->expectExceptionMessage('The profiler must be enabled.'); + $controller->homeAction(); } @@ -110,13 +111,14 @@ public function testPanelActionWithValidPanelAndToken() public function testToolbarActionWithProfilerDisabled() { - $this->expectException(NotFoundHttpException::class); - $this->expectExceptionMessage('The profiler must be enabled.'); - $urlGenerator = $this->createMock(UrlGeneratorInterface::class); $twig = $this->createMock(Environment::class); $controller = new ProfilerController($urlGenerator, null, $twig, []); + + $this->expectException(NotFoundHttpException::class); + $this->expectExceptionMessage('The profiler must be enabled.'); + $controller->toolbarAction(Request::create('/_wdt/foo-token'), null); } @@ -202,13 +204,14 @@ public function testReturns404onTokenNotFound($withCsp) public function testSearchBarActionWithProfilerDisabled() { - $this->expectException(NotFoundHttpException::class); - $this->expectExceptionMessage('The profiler must be enabled.'); - $urlGenerator = $this->createMock(UrlGeneratorInterface::class); $twig = $this->createMock(Environment::class); $controller = new ProfilerController($urlGenerator, null, $twig, []); + + $this->expectException(NotFoundHttpException::class); + $this->expectExceptionMessage('The profiler must be enabled.'); + $controller->searchBarAction(Request::create('/_profiler/search_bar')); } @@ -296,13 +299,14 @@ public function testSearchResultsAction($withCsp) public function testSearchActionWithProfilerDisabled() { - $this->expectException(NotFoundHttpException::class); - $this->expectExceptionMessage('The profiler must be enabled.'); - $urlGenerator = $this->createMock(UrlGeneratorInterface::class); $twig = $this->createMock(Environment::class); $controller = new ProfilerController($urlGenerator, null, $twig, []); + + $this->expectException(NotFoundHttpException::class); + $this->expectExceptionMessage('The profiler must be enabled.'); + $controller->searchBarAction(Request::create('/_profiler/search')); } @@ -335,13 +339,14 @@ public function testSearchActionWithoutToken() public function testPhpinfoActionWithProfilerDisabled() { - $this->expectException(NotFoundHttpException::class); - $this->expectExceptionMessage('The profiler must be enabled.'); - $urlGenerator = $this->createMock(UrlGeneratorInterface::class); $twig = $this->createMock(Environment::class); $controller = new ProfilerController($urlGenerator, null, $twig, []); + + $this->expectException(NotFoundHttpException::class); + $this->expectExceptionMessage('The profiler must be enabled.'); + $controller->phpinfoAction(); } @@ -357,26 +362,28 @@ public function testPhpinfoAction() public function testFontActionWithProfilerDisabled() { - $this->expectException(NotFoundHttpException::class); - $this->expectExceptionMessage('The profiler must be enabled.'); - $urlGenerator = $this->createMock(UrlGeneratorInterface::class); $twig = $this->createMock(Environment::class); $controller = new ProfilerController($urlGenerator, null, $twig, []); + + $this->expectException(NotFoundHttpException::class); + $this->expectExceptionMessage('The profiler must be enabled.'); + $controller->fontAction('JetBrainsMono'); } public function testFontActionWithInvalidFontName() { - $this->expectException(NotFoundHttpException::class); - $this->expectExceptionMessage('Font file "InvalidFontName.woff2" not found.'); - $urlGenerator = $this->createMock(UrlGeneratorInterface::class); $profiler = $this->createMock(Profiler::class); $twig = $this->createMock(Environment::class); $controller = new ProfilerController($urlGenerator, $profiler, $twig, []); + + $this->expectException(NotFoundHttpException::class); + $this->expectExceptionMessage('Font file "InvalidFontName.woff2" not found.'); + $controller->fontAction('InvalidFontName'); } diff --git a/src/Symfony/Component/Asset/Tests/PackagesTest.php b/src/Symfony/Component/Asset/Tests/PackagesTest.php index 54ded7d4c1420..bdbd21d5bd633 100644 --- a/src/Symfony/Component/Asset/Tests/PackagesTest.php +++ b/src/Symfony/Component/Asset/Tests/PackagesTest.php @@ -61,14 +61,12 @@ public function testGetUrl() public function testNoDefaultPackage() { $this->expectException(LogicException::class); - $packages = new Packages(); - $packages->getPackage(); + (new Packages())->getPackage(); } public function testUndefinedPackage() { $this->expectException(InvalidArgumentException::class); - $packages = new Packages(); - $packages->getPackage('a'); + (new Packages())->getPackage('a'); } } diff --git a/src/Symfony/Component/Asset/Tests/UrlPackageTest.php b/src/Symfony/Component/Asset/Tests/UrlPackageTest.php index 69cc8418fcff5..db17fc67a505c 100644 --- a/src/Symfony/Component/Asset/Tests/UrlPackageTest.php +++ b/src/Symfony/Component/Asset/Tests/UrlPackageTest.php @@ -110,7 +110,7 @@ public function testNoBaseUrls() /** * @dataProvider getWrongBaseUrlConfig */ - public function testWrongBaseUrl($baseUrls) + public function testWrongBaseUrl(string $baseUrls) { $this->expectException(InvalidArgumentException::class); new UrlPackage($baseUrls, new EmptyVersionStrategy()); diff --git a/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php index c8cb3fbe49466..2534e90e94579 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php @@ -101,12 +101,13 @@ public function testDefaultOptions() public function testOptionSerializer() { - $this->expectException(CacheException::class); - $this->expectExceptionMessage('MemcachedAdapter: "serializer" option must be "php" or "igbinary".'); if (!\Memcached::HAVE_JSON) { $this->markTestSkipped('Memcached::HAVE_JSON required'); } + $this->expectException(CacheException::class); + $this->expectExceptionMessage('MemcachedAdapter: "serializer" option must be "php" or "igbinary".'); + new MemcachedAdapter(MemcachedAdapter::createConnection([], ['serializer' => 'json'])); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php index 612e5d09c3434..71122a98b6740 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php @@ -40,14 +40,16 @@ public function createCachePool(int $defaultLifetime = 0, string $testMethod = n public function testProxyfiedItem() { - $this->expectException(\Exception::class); - $this->expectExceptionMessage('OK bar'); $item = new CacheItem(); $pool = new ProxyAdapter(new TestingArrayAdapter($item)); $proxyItem = $pool->getItem('foo'); $this->assertNotSame($item, $proxyItem); + + $this->expectException(\Exception::class); + $this->expectExceptionMessage('OK bar'); + $pool->save($proxyItem->set('bar')); } } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterSentinelTest.php b/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterSentinelTest.php index db26377632cd1..0e751d91aa052 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterSentinelTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterSentinelTest.php @@ -37,9 +37,11 @@ public static function setUpBeforeClass(): void public function testInvalidDSNHasBothClusterAndSentinel() { + $dsn = 'redis:?host[redis1]&host[redis2]&host[redis3]&redis_cluster=1&redis_sentinel=mymaster'; + $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/TagAwareTestTrait.php b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareTestTrait.php index 2ea50210841b3..8ec1297ea24e4 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareTestTrait.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareTestTrait.php @@ -22,9 +22,11 @@ trait TagAwareTestTrait { public function testInvalidTag() { - $this->expectException(\Psr\Cache\InvalidArgumentException::class); $pool = $this->createCachePool(); $item = $pool->getItem('foo'); + + $this->expectException(\Psr\Cache\InvalidArgumentException::class); + $item->tag(':'); } diff --git a/src/Symfony/Component/Cache/Tests/CacheItemTest.php b/src/Symfony/Component/Cache/Tests/CacheItemTest.php index 01358e967c89e..49ee1af4ffa50 100644 --- a/src/Symfony/Component/Cache/Tests/CacheItemTest.php +++ b/src/Symfony/Component/Cache/Tests/CacheItemTest.php @@ -76,23 +76,25 @@ public function testTag() */ public function testInvalidTag($tag) { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Cache tag'); $item = new CacheItem(); $r = new \ReflectionProperty($item, 'isTaggable'); $r->setValue($item, true); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cache tag'); + $item->tag($tag); } public function testNonTaggableItem() { - $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'); $r->setValue($item, 'foo'); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cache item "foo" comes from a non tag-aware pool: you cannot tag it.'); + $item->tag([]); } } diff --git a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPassTest.php b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPassTest.php index cdb361a5633d7..18647fb283cdf 100644 --- a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPassTest.php +++ b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPassTest.php @@ -179,8 +179,6 @@ public function testWithNameAttribute() public function testThrowsExceptionWhenCachePoolTagHasUnknownAttributes() { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Invalid "cache.pool" tag for service "app.cache_pool": accepted attributes are'); $container = new ContainerBuilder(); $container->setParameter('kernel.container_class', 'app'); $container->setParameter('kernel.project_dir', 'foo'); @@ -192,6 +190,9 @@ public function testThrowsExceptionWhenCachePoolTagHasUnknownAttributes() $cachePool->addTag('cache.pool', ['foobar' => 123]); $container->setDefinition('app.cache_pool', $cachePool); + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid "cache.pool" tag for service "app.cache_pool": accepted attributes are'); + $this->cachePoolPass->process($container); } diff --git a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php index 8329cd2bd7fc7..e86d815502de3 100644 --- a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php +++ b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php @@ -59,13 +59,15 @@ public function testCompilePassIsIgnoredIfCommandDoesNotExist() public function testCompilerPassThrowsOnInvalidDefinitionClass() { - $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([]); $container->register('pool.not-found', NotFound::class)->addTag('cache.pool'); $pass = new CachePoolPrunerPass(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Class "Symfony\Component\Cache\Tests\DependencyInjection\NotFound" used for service "pool.not-found" cannot be found.'); + $pass->process($container); } } diff --git a/src/Symfony/Component/Cache/Tests/Marshaller/DefaultMarshallerTest.php b/src/Symfony/Component/Cache/Tests/Marshaller/DefaultMarshallerTest.php index bf97b61368586..45b7927861e26 100644 --- a/src/Symfony/Component/Cache/Tests/Marshaller/DefaultMarshallerTest.php +++ b/src/Symfony/Component/Cache/Tests/Marshaller/DefaultMarshallerTest.php @@ -58,8 +58,7 @@ public function testNativeUnserializeNotFoundClass() { $this->expectException(\DomainException::class); $this->expectExceptionMessage('Class not found: NotExistingClass'); - $marshaller = new DefaultMarshaller(); - $marshaller->unmarshall('O:16:"NotExistingClass":0:{}'); + (new DefaultMarshaller())->unmarshall('O:16:"NotExistingClass":0:{}'); } /** diff --git a/src/Symfony/Component/Config/Tests/ConfigCacheFactoryTest.php b/src/Symfony/Component/Config/Tests/ConfigCacheFactoryTest.php index 7596d7956c7c0..0141a7345a196 100644 --- a/src/Symfony/Component/Config/Tests/ConfigCacheFactoryTest.php +++ b/src/Symfony/Component/Config/Tests/ConfigCacheFactoryTest.php @@ -18,9 +18,10 @@ class ConfigCacheFactoryTest extends TestCase { public function testCacheWithInvalidCallback() { - $this->expectException(\TypeError::class); $cacheFactory = new ConfigCacheFactory(true); + $this->expectException(\TypeError::class); + $cacheFactory->cache('file', new \stdClass()); } } diff --git a/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php index 6b713ca461d4a..5212ef7c7091a 100644 --- a/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php @@ -21,37 +21,45 @@ class ArrayNodeTest extends TestCase { public function testNormalizeThrowsExceptionWhenFalseIsNotAllowed() { - $this->expectException(InvalidTypeException::class); $node = new ArrayNode('root'); + + $this->expectException(InvalidTypeException::class); + $node->normalize(false); } public function testExceptionThrownOnUnrecognizedChild() { + $node = new ArrayNode('root'); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('Unrecognized option "foo" under "root"'); - $node = new ArrayNode('root'); + $node->normalize(['foo' => 'bar']); } public function testNormalizeWithProposals() { - $this->expectException(InvalidConfigurationException::class); - $this->expectExceptionMessage('Did you mean "alpha1", "alpha2"?'); $node = new ArrayNode('root'); $node->addChild(new ArrayNode('alpha1')); $node->addChild(new ArrayNode('alpha2')); $node->addChild(new ArrayNode('beta')); + + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('Did you mean "alpha1", "alpha2"?'); + $node->normalize(['alpha3' => 'foo']); } public function testNormalizeWithoutProposals() { - $this->expectException(InvalidConfigurationException::class); - $this->expectExceptionMessage('Available options are "alpha1", "alpha2".'); $node = new ArrayNode('root'); $node->addChild(new ArrayNode('alpha1')); $node->addChild(new ArrayNode('alpha2')); + + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('Available options are "alpha1", "alpha2".'); + $node->normalize(['beta' => 'foo']); } @@ -193,32 +201,38 @@ public static function getPreNormalizedNormalizedOrderedData(): array public function testAddChildEmptyName() { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Child nodes must be named.'); $node = new ArrayNode('root'); $childNode = new ArrayNode(''); + + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Child nodes must be named.'); + $node->addChild($childNode); } public function testAddChildNameAlreadyExists() { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('A child node named "foo" already exists.'); $node = new ArrayNode('root'); $childNode = new ArrayNode('foo'); $node->addChild($childNode); $childNodeWithSameName = new ArrayNode('foo'); + + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('A child node named "foo" already exists.'); + $node->addChild($childNodeWithSameName); } public function testGetDefaultValueWithoutDefaultValue() { + $node = new ArrayNode('foo'); + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('The node at path "foo" has no default value.'); - $node = new ArrayNode('foo'); + $node->getDefaultValue(); } @@ -267,8 +281,6 @@ public function testSetDeprecated() */ public function testMergeWithoutIgnoringExtraKeys(array $prenormalizeds) { - $this->expectException(\RuntimeException::class); - $this->expectExceptionMessage('merge() expects a normalized config array.'); $node = new ArrayNode('root'); $node->addChild(new ScalarNode('foo')); $node->addChild(new ScalarNode('bar')); @@ -276,6 +288,9 @@ public function testMergeWithoutIgnoringExtraKeys(array $prenormalizeds) $r = new \ReflectionMethod($node, 'mergeValues'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('merge() expects a normalized config array.'); + $r->invoke($node, ...$prenormalizeds); } @@ -284,8 +299,6 @@ public function testMergeWithoutIgnoringExtraKeys(array $prenormalizeds) */ public function testMergeWithIgnoringAndRemovingExtraKeys(array $prenormalizeds) { - $this->expectException(\RuntimeException::class); - $this->expectExceptionMessage('merge() expects a normalized config array.'); $node = new ArrayNode('root'); $node->addChild(new ScalarNode('foo')); $node->addChild(new ScalarNode('bar')); @@ -293,6 +306,9 @@ public function testMergeWithIgnoringAndRemovingExtraKeys(array $prenormalizeds) $r = new \ReflectionMethod($node, 'mergeValues'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('merge() expects a normalized config array.'); + $r->invoke($node, ...$prenormalizeds); } diff --git a/src/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.php index e29e047ef0fb4..f617148ff9e17 100644 --- a/src/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.php @@ -50,8 +50,11 @@ public static function getValidValues(): array */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { - $this->expectException(InvalidTypeException::class); + $node = new BooleanNode('test'); + + $this->expectException(InvalidTypeException::class); + $node->normalize($value); } diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.php index 06ce62e809161..e59589601720c 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.php @@ -21,71 +21,85 @@ class NumericNodeDefinitionTest extends TestCase { public function testIncoherentMinAssertion() { + $node = new IntegerNodeDefinition('foo'); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('You cannot define a min(4) as you already have a max(3)'); - $def = new IntegerNodeDefinition('foo'); - $def->max(3)->min(4); + + $node->max(3)->min(4); } public function testIncoherentMaxAssertion() { + $node = new IntegerNodeDefinition('foo'); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('You cannot define a max(2) as you already have a min(3)'); - $node = new IntegerNodeDefinition('foo'); + $node->min(3)->max(2); } public function testIntegerMinAssertion() { + $node = new IntegerNodeDefinition('foo'); + $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); + + $node->min(5)->getNode()->finalize(4); } public function testIntegerMaxAssertion() { + $node = new IntegerNodeDefinition('foo'); + $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); + + $node->max(3)->getNode()->finalize(4); } public function testIntegerValidMinMaxAssertion() { - $def = new IntegerNodeDefinition('foo'); - $node = $def->min(3)->max(7)->getNode(); + $node = new IntegerNodeDefinition('foo'); + $node = $node->min(3)->max(7)->getNode(); $this->assertEquals(4, $node->finalize(4)); } public function testFloatMinAssertion() { + $node = new FloatNodeDefinition('foo'); + $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); + + $node->min(5E2)->getNode()->finalize(4e2); } public function testFloatMaxAssertion() { + $node = new FloatNodeDefinition('foo'); + $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); + + $node->max(0.3)->getNode()->finalize(4.3); } public function testFloatValidMinMaxAssertion() { - $def = new FloatNodeDefinition('foo'); - $node = $def->min(3.0)->max(7e2)->getNode(); + $node = new FloatNodeDefinition('foo'); + $node = $node->min(3.0)->max(7e2)->getNode(); $this->assertEquals(4.5, $node->finalize(4.5)); } public function testCannotBeEmptyThrowsAnException() { + $node = new IntegerNodeDefinition('foo'); + $this->expectException(InvalidDefinitionException::class); $this->expectExceptionMessage('->cannotBeEmpty() is not applicable to NumericNodeDefinition.'); - $def = new IntegerNodeDefinition('foo'); - $def->cannotBeEmpty(); + + $node->cannotBeEmpty(); } } diff --git a/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php index f71a09cd14a1c..48bfc4895d1a4 100644 --- a/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php @@ -53,9 +53,11 @@ public function testConstructionWithNullName() public function testFinalizeWithInvalidValue() { + $node = new EnumNode('foo', null, ['foo', 'bar', TestEnum::Foo]); + $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('The value "foobar" is not allowed for path "foo". Permissible values: "foo", "bar", Symfony\Component\Config\Tests\Fixtures\TestEnum::Foo'); - $node = new EnumNode('foo', null, ['foo', 'bar', TestEnum::Foo]); + $node->finalize('foobar'); } diff --git a/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php index eb3f7c47a41df..9d18b5899682c 100644 --- a/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php @@ -56,8 +56,10 @@ public static function getValidValues(): array */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { - $this->expectException(InvalidTypeException::class); $node = new FloatNode('test'); + + $this->expectException(InvalidTypeException::class); + $node->normalize($value); } diff --git a/src/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.php index 132b6b43b654d..6ab60032d23b1 100644 --- a/src/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.php @@ -51,8 +51,10 @@ public static function getValidValues(): array */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { - $this->expectException(InvalidTypeException::class); $node = new IntegerNode('test'); + + $this->expectException(InvalidTypeException::class); + $node->normalize($value); } diff --git a/src/Symfony/Component/Config/Tests/Definition/MergeTest.php b/src/Symfony/Component/Config/Tests/Definition/MergeTest.php index bc7d9670406b7..384196e825627 100644 --- a/src/Symfony/Component/Config/Tests/Definition/MergeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/MergeTest.php @@ -20,7 +20,6 @@ class MergeTest extends TestCase { public function testForbiddenOverwrite() { - $this->expectException(ForbiddenOverwriteException::class); $tb = new TreeBuilder('root', 'array'); $tree = $tb ->getRootNode() @@ -41,6 +40,8 @@ public function testForbiddenOverwrite() 'foo' => 'moo', ]; + $this->expectException(ForbiddenOverwriteException::class); + $tree->merge($a, $b); } @@ -94,7 +95,6 @@ public function testUnsetKey() public function testDoesNotAllowNewKeysInSubsequentConfigs() { - $this->expectException(InvalidConfigurationException::class); $tb = new TreeBuilder('root', 'array'); $tree = $tb ->getRootNode() @@ -124,6 +124,8 @@ public function testDoesNotAllowNewKeysInSubsequentConfigs() ], ]; + $this->expectException(InvalidConfigurationException::class); + $tree->merge($a, $b); } diff --git a/src/Symfony/Component/Config/Tests/Definition/NormalizationTest.php b/src/Symfony/Component/Config/Tests/Definition/NormalizationTest.php index 8febd867baaa6..3bf489ee1b50d 100644 --- a/src/Symfony/Component/Config/Tests/Definition/NormalizationTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/NormalizationTest.php @@ -170,14 +170,15 @@ public static function getNumericKeysTests(): array public function testNonAssociativeArrayThrowsExceptionIfAttributeNotSet() { - $this->expectException(InvalidConfigurationException::class); - $this->expectExceptionMessage('The attribute "id" must be set for path "root.thing".'); $denormalized = [ 'thing' => [ ['foo', 'bar'], ['baz', 'qux'], ], ]; + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('The attribute "id" must be set for path "root.thing".'); + $this->assertNormalized($this->getNumericKeysTestTree(), $denormalized, []); } diff --git a/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php index bd116b69593cd..eea3d49b499cd 100644 --- a/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php @@ -88,8 +88,10 @@ public function testSetDeprecated() */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { - $this->expectException(InvalidTypeException::class); $node = new ScalarNode('test'); + + $this->expectException(InvalidTypeException::class); + $node->normalize($value); } @@ -156,9 +158,11 @@ public static function getValidNonEmptyValues(): array */ public function testNotAllowedEmptyValuesThrowException($value) { - $this->expectException(InvalidConfigurationException::class); $node = new ScalarNode('test'); $node->setAllowEmptyValue(false); + + $this->expectException(InvalidConfigurationException::class); + $node->finalize($value); } diff --git a/src/Symfony/Component/Config/Tests/FileLocatorTest.php b/src/Symfony/Component/Config/Tests/FileLocatorTest.php index 0c841eb85ab5a..d042bff7d9f69 100644 --- a/src/Symfony/Component/Config/Tests/FileLocatorTest.php +++ b/src/Symfony/Component/Config/Tests/FileLocatorTest.php @@ -88,26 +88,29 @@ public function testLocate() public function testLocateThrowsAnExceptionIfTheFileDoesNotExists() { + $loader = new FileLocator([__DIR__.'/Fixtures']); + $this->expectException(FileLocatorFileNotFoundException::class); $this->expectExceptionMessage('The file "foobar.xml" does not exist'); - $loader = new FileLocator([__DIR__.'/Fixtures']); $loader->locate('foobar.xml', __DIR__); } public function testLocateThrowsAnExceptionIfTheFileDoesNotExistsInAbsolutePath() { - $this->expectException(FileLocatorFileNotFoundException::class); $loader = new FileLocator([__DIR__.'/Fixtures']); + $this->expectException(FileLocatorFileNotFoundException::class); + $loader->locate(__DIR__.'/Fixtures/foobar.xml', __DIR__); } public function testLocateEmpty() { + $loader = new FileLocator([__DIR__.'/Fixtures']); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('An empty file name is not valid to be located.'); - $loader = new FileLocator([__DIR__.'/Fixtures']); $loader->locate('', __DIR__); } diff --git a/src/Symfony/Component/Config/Tests/Loader/DelegatingLoaderTest.php b/src/Symfony/Component/Config/Tests/Loader/DelegatingLoaderTest.php index 4f689775f7b14..8fb70532e2881 100644 --- a/src/Symfony/Component/Config/Tests/Loader/DelegatingLoaderTest.php +++ b/src/Symfony/Component/Config/Tests/Loader/DelegatingLoaderTest.php @@ -60,12 +60,13 @@ public function testLoad() public function testLoadThrowsAnExceptionIfTheResourceCannotBeLoaded() { - $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); + $this->expectException(LoaderLoadException::class); + $loader->load('foo'); } } diff --git a/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php b/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php index 5c87194eeec74..385103cebe2ec 100644 --- a/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php +++ b/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php @@ -48,7 +48,6 @@ public function testResolve() public function testResolveWhenResolverCannotFindLoader() { - $this->expectException(LoaderLoadException::class); $resolver = $this->createMock(LoaderResolverInterface::class); $resolver->expects($this->once()) ->method('resolve') @@ -58,6 +57,8 @@ public function testResolveWhenResolverCannotFindLoader() $loader = new ProjectLoader1(); $loader->setResolver($resolver); + $this->expectException(LoaderLoadException::class); + $loader->resolve('FOOBAR'); } diff --git a/src/Symfony/Component/Config/Tests/Resource/ClassExistenceResourceTest.php b/src/Symfony/Component/Config/Tests/Resource/ClassExistenceResourceTest.php index 733c47e40b334..32093d975dd0e 100644 --- a/src/Symfony/Component/Config/Tests/Resource/ClassExistenceResourceTest.php +++ b/src/Symfony/Component/Config/Tests/Resource/ClassExistenceResourceTest.php @@ -85,28 +85,31 @@ public function testBadParentWithTimestamp() public function testBadParentWithNoTimestamp() { + $res = new ClassExistenceResource(BadParent::class, false); + $this->expectException(\ReflectionException::class); $this->expectExceptionMessage('Class "Symfony\Component\Config\Tests\Fixtures\MissingParent" not found while loading "Symfony\Component\Config\Tests\Fixtures\BadParent".'); - $res = new ClassExistenceResource(BadParent::class, false); $res->isFresh(0); } public function testBadFileName() { + $res = new ClassExistenceResource(BadFileName::class, false); + $this->expectException(\ReflectionException::class); $this->expectExceptionMessage('Mismatch between file name and class name.'); - $res = new ClassExistenceResource(BadFileName::class, false); $res->isFresh(0); } public function testBadFileNameBis() { + $res = new ClassExistenceResource(BadFileName::class, false); + $this->expectException(\ReflectionException::class); $this->expectExceptionMessage('Mismatch between file name and class name.'); - $res = new ClassExistenceResource(BadFileName::class, false); $res->isFresh(0); } @@ -119,9 +122,10 @@ public function testConditionalClass() public function testParseError() { + $res = new ClassExistenceResource(ParseError::class, false); + $this->expectException(\ParseError::class); - $res = new ClassExistenceResource(ParseError::class, false); $res->isFresh(0); } } diff --git a/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php b/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php index 4bebb823e4ed3..9d8761333b9f1 100644 --- a/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php +++ b/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php @@ -91,13 +91,14 @@ public function testLoadFile() public function testParseWithInvalidValidatorCallable() { - $this->expectException(InvalidXmlException::class); - $this->expectExceptionMessage('The XML is not valid'); $fixtures = __DIR__.'/../Fixtures/Util/'; $mock = $this->createMock(Validator::class); $mock->expects($this->once())->method('validate')->willReturn(false); + $this->expectException(InvalidXmlException::class); + $this->expectExceptionMessage('The XML is not valid'); + 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 68bb459e82812..f575f5e52d0b8 100644 --- a/src/Symfony/Component/Console/Tests/ApplicationTest.php +++ b/src/Symfony/Component/Console/Tests/ApplicationTest.php @@ -229,8 +229,8 @@ public function testAddCommandWithEmptyConstructor() { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Command class "Foo5Command" is not correctly initialized. You probably forgot to call the parent constructor.'); - $application = new Application(); - $application->add(new \Foo5Command()); + + (new Application())->add(new \Foo5Command()); } public function testHasGet() @@ -294,8 +294,8 @@ public function testGetInvalidCommand() { $this->expectException(CommandNotFoundException::class); $this->expectExceptionMessage('The command "foofoo" does not exist.'); - $application = new Application(); - $application->get('foofoo'); + + (new Application())->get('foofoo'); } public function testGetNamespaces() @@ -351,20 +351,21 @@ public function testFindInvalidNamespace() { $this->expectException(NamespaceNotFoundException::class); $this->expectExceptionMessage('There are no commands defined in the "bar" namespace.'); - $application = new Application(); - $application->findNamespace('bar'); + + (new Application)->findNamespace('bar'); } public function testFindUniqueNameButNamespaceName() { - $this->expectException(CommandNotFoundException::class); - $this->expectExceptionMessage('Command "foo1" is not defined'); $application = new Application(); $application->add(new \FooCommand()); $application->add(new \Foo1Command()); $application->add(new \Foo2Command()); - $application->find($commandName = 'foo1'); + $this->expectException(CommandNotFoundException::class); + $this->expectExceptionMessage('Command "foo1" is not defined'); + + $application->find('foo1'); } public function testFind() @@ -403,13 +404,14 @@ public function testFindCaseInsensitiveAsFallback() public function testFindCaseInsensitiveSuggestions() { - $this->expectException(CommandNotFoundException::class); - $this->expectExceptionMessage('Command "FoO:BaR" is ambiguous'); $application = new Application(); $application->add(new \FooSameCaseLowercaseCommand()); $application->add(new \FooSameCaseUppercaseCommand()); - $this->assertInstanceOf(\FooSameCaseLowercaseCommand::class, $application->find('FoO:BaR'), '->find() will find two suggestions with case insensitivity'); + $this->expectException(CommandNotFoundException::class); + $this->expectExceptionMessage('Command "FoO:BaR" is ambiguous'); + + $application->find('FoO:BaR'); } public function testFindWithCommandLoader() @@ -506,10 +508,12 @@ public function testFindCommandWithMissingNamespace() */ public function testFindAlternativeExceptionMessageSingle($name) { - $this->expectException(CommandNotFoundException::class); - $this->expectExceptionMessage('Did you mean this'); $application = new Application(); $application->add(new \Foo3Command()); + + $this->expectException(CommandNotFoundException::class); + $this->expectExceptionMessage('Did you mean this'); + $application->find($name); } @@ -744,11 +748,13 @@ public function testFindNamespaceDoesNotFailOnDeepSimilarNamespaces() public function testFindWithDoubleColonInNameThrowsException() { - $this->expectException(CommandNotFoundException::class); - $this->expectExceptionMessage('Command "foo::bar" is not defined.'); $application = new Application(); $application->add(new \FooCommand()); $application->add(new \Foo4Command()); + + $this->expectException(CommandNotFoundException::class); + $this->expectExceptionMessage('Command "foo::bar" is not defined.'); + $application->find('foo::bar'); } @@ -1248,8 +1254,6 @@ public function testRunReturnsExitCodeOneForNegativeExceptionCode($exceptionCode public function testAddingOptionWithDuplicateShortcut() { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('An option with shortcut "e" already exists.'); $dispatcher = new EventDispatcher(); $application = new Application(); $application->setAutoExit(false); @@ -1268,6 +1272,9 @@ public function testAddingOptionWithDuplicateShortcut() $input = new ArrayInput(['command' => 'foo']); $output = new NullOutput(); + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('An option with shortcut "e" already exists.'); + $application->run($input, $output); } @@ -1276,7 +1283,6 @@ public function testAddingOptionWithDuplicateShortcut() */ public function testAddingAlreadySetDefinitionElementData($def) { - $this->expectException(\LogicException::class); $application = new Application(); $application->setAutoExit(false); $application->setCatchExceptions(false); @@ -1288,10 +1294,13 @@ public function testAddingAlreadySetDefinitionElementData($def) $input = new ArrayInput(['command' => 'foo']); $output = new NullOutput(); + + $this->expectException(\LogicException::class); + $application->run($input, $output); } - public static function getAddingAlreadySetDefinitionElementData() + public static function getAddingAlreadySetDefinitionElementData(): array { return [ [new InputArgument('command', InputArgument::REQUIRED)], @@ -1428,8 +1437,6 @@ public function testRunWithDispatcher() public function testRunWithExceptionAndDispatcher() { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('error'); $application = new Application(); $application->setDispatcher($this->getDispatcher()); $application->setAutoExit(false); @@ -1440,6 +1447,10 @@ public function testRunWithExceptionAndDispatcher() }); $tester = new ApplicationTester($application); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('error'); + $tester->run(['command' => 'foo']); } @@ -1504,9 +1515,6 @@ public function testRunWithError() public function testRunWithFindError() { - $this->expectException(\Error::class); - $this->expectExceptionMessage('Find exception'); - $application = new Application(); $application->setAutoExit(false); $application->setCatchExceptions(false); @@ -1518,6 +1526,10 @@ public function testRunWithFindError() // The exception should not be ignored $tester = new ApplicationTester($application); + + $this->expectException(\Error::class); + $this->expectExceptionMessage('Find exception'); + $tester->run(['command' => 'foo']); } @@ -1590,8 +1602,6 @@ public function testErrorIsRethrownIfNotHandledByConsoleErrorEvent() public function testRunWithErrorAndDispatcher() { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('error'); $application = new Application(); $application->setDispatcher($this->getDispatcher()); $application->setAutoExit(false); @@ -1604,6 +1614,10 @@ public function testRunWithErrorAndDispatcher() }); $tester = new ApplicationTester($application); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('error'); + $tester->run(['command' => 'dym']); $this->assertStringContainsString('before.dym.error.after.', $tester->getDisplay(), 'The PHP error did not dispatch events'); } @@ -1802,9 +1816,11 @@ public function testRunLazyCommandService() public function testGetDisabledLazyCommand() { - $this->expectException(CommandNotFoundException::class); $application = new Application(); $application->setCommandLoader(new FactoryCommandLoader(['disabled' => fn () => new DisabledCommand()])); + + $this->expectException(CommandNotFoundException::class); + $application->get('disabled'); } @@ -1895,8 +1911,6 @@ public function testErrorIsRethrownIfNotHandledByConsoleErrorEventWithCatchingEn public function testThrowingErrorListener() { - $this->expectException(\RuntimeException::class); - $this->expectExceptionMessage('foo'); $dispatcher = $this->getDispatcher(); $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) { throw new \RuntimeException('foo'); @@ -1916,20 +1930,25 @@ public function testThrowingErrorListener() }); $tester = new ApplicationTester($application); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('foo'); + $tester->run(['command' => 'foo']); } public function testCommandNameMismatchWithCommandLoaderKeyThrows() { - $this->expectException(CommandNotFoundException::class); - $this->expectExceptionMessage('The "test" command cannot be found because it is registered under multiple names. Make sure you don\'t set a different name via constructor or "setName()".'); - $app = new Application(); $loader = new FactoryCommandLoader([ 'test' => static fn () => new Command('test-command'), ]); $app->setCommandLoader($loader); + + $this->expectException(CommandNotFoundException::class); + $this->expectExceptionMessage('The "test" command cannot be found because it is registered under multiple names. Make sure you don\'t set a different name via constructor or "setName()".'); + $app->get('test'); } diff --git a/src/Symfony/Component/Console/Tests/Command/CommandTest.php b/src/Symfony/Component/Console/Tests/Command/CommandTest.php index 99fc554b5738c..76dacfadb3cb7 100644 --- a/src/Symfony/Component/Console/Tests/Command/CommandTest.php +++ b/src/Symfony/Component/Console/Tests/Command/CommandTest.php @@ -144,11 +144,10 @@ public function testInvalidCommandNames($name) $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage(sprintf('Command name "%s" is invalid.', $name)); - $command = new \TestCommand(); - $command->setName($name); + (new \TestCommand())->setName($name); } - public static function provideInvalidCommandNames() + public static function provideInvalidCommandNames(): array { return [ [''], @@ -236,8 +235,7 @@ public function testGetHelperWithoutHelperSet() { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot retrieve helper "formatter" because there is no HelperSet defined.'); - $command = new \TestCommand(); - $command->getHelper('formatter'); + (new \TestCommand())->getHelper('formatter'); } public function testMergeApplicationDefinition() @@ -305,16 +303,17 @@ public function testExecuteMethodNeedsToBeOverridden() { $this->expectException(\LogicException::class); $this->expectExceptionMessage('You must override the execute() method in the concrete command class.'); - $command = new Command('foo'); - $command->run(new StringInput(''), new NullOutput()); + (new Command('foo'))->run(new StringInput(''), new NullOutput()); } public function testRunWithInvalidOption() { - $this->expectException(InvalidOptionException::class); - $this->expectExceptionMessage('The "--bar" option does not exist.'); $command = new \TestCommand(); $tester = new CommandTester($command); + + $this->expectException(InvalidOptionException::class); + $this->expectExceptionMessage('The "--bar" option does not exist.'); + $tester->execute(['--bar' => true]); } diff --git a/src/Symfony/Component/Console/Tests/DependencyInjection/AddConsoleCommandPassTest.php b/src/Symfony/Component/Console/Tests/DependencyInjection/AddConsoleCommandPassTest.php index 6819282a33fe2..639e5091ef22e 100644 --- a/src/Symfony/Component/Console/Tests/DependencyInjection/AddConsoleCommandPassTest.php +++ b/src/Symfony/Component/Console/Tests/DependencyInjection/AddConsoleCommandPassTest.php @@ -180,8 +180,6 @@ public function testEscapesDefaultFromPhp() public function testProcessThrowAnExceptionIfTheServiceIsAbstract() { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The service "my-command" tagged "console.command" must not be abstract.'); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->addCompilerPass(new AddConsoleCommandPass(), PassConfig::TYPE_BEFORE_REMOVING); @@ -191,13 +189,14 @@ public function testProcessThrowAnExceptionIfTheServiceIsAbstract() $definition->setAbstract(true); $container->setDefinition('my-command', $definition); + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The service "my-command" tagged "console.command" must not be abstract.'); + $container->compile(); } public function testProcessThrowAnExceptionIfTheServiceIsNotASubclassOfCommand() { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The service "my-command" tagged "console.command" must be a subclass of "Symfony\Component\Console\Command\Command".'); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->addCompilerPass(new AddConsoleCommandPass(), PassConfig::TYPE_BEFORE_REMOVING); @@ -206,6 +205,9 @@ public function testProcessThrowAnExceptionIfTheServiceIsNotASubclassOfCommand() $definition->addTag('console.command'); $container->setDefinition('my-command', $definition); + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The service "my-command" tagged "console.command" must be a subclass of "Symfony\Component\Console\Command\Command".'); + $container->compile(); } @@ -281,8 +283,6 @@ public function testProcessOnChildDefinitionWithParentClass() public function testProcessOnChildDefinitionWithoutClass() { - $this->expectException(\RuntimeException::class); - $this->expectExceptionMessage('The definition for "my-child-command" has no class.'); $container = new ContainerBuilder(); $container->addCompilerPass(new AddConsoleCommandPass(), PassConfig::TYPE_BEFORE_REMOVING); @@ -298,6 +298,9 @@ public function testProcessOnChildDefinitionWithoutClass() $container->setDefinition($parentId, $parentDefinition); $container->setDefinition($childId, $childDefinition); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('The definition for "my-child-command" has no class.'); + $container->compile(); } } diff --git a/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterStyleStackTest.php b/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterStyleStackTest.php index 7fbe4f415182d..0ceab34ea150f 100644 --- a/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterStyleStackTest.php +++ b/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterStyleStackTest.php @@ -61,9 +61,11 @@ public function testPopNotLast() public function testInvalidPop() { - $this->expectException(\InvalidArgumentException::class); $stack = new OutputFormatterStyleStack(); $stack->push(new OutputFormatterStyle('white', 'black')); + + $this->expectException(\InvalidArgumentException::class); + $stack->pop(new OutputFormatterStyle('yellow', 'blue')); } } diff --git a/src/Symfony/Component/Console/Tests/Helper/ProgressIndicatorTest.php b/src/Symfony/Component/Console/Tests/Helper/ProgressIndicatorTest.php index ffb3472eca11c..7f7dbc0a015e0 100644 --- a/src/Symfony/Component/Console/Tests/Helper/ProgressIndicatorTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/ProgressIndicatorTest.php @@ -118,10 +118,12 @@ public function testCannotSetInvalidIndicatorCharacters() public function testCannotStartAlreadyStartedIndicator() { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('Progress indicator already started.'); $bar = new ProgressIndicator($this->getOutputStream()); $bar->start('Starting...'); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('Progress indicator already started.'); + $bar->start('Starting Again.'); } diff --git a/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php b/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php index 9a37558eced2d..8c5fe8a20a3ff 100644 --- a/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php @@ -677,8 +677,6 @@ public function testSelectChoiceFromChoiceList($providedAnswer, $expectedValue) public function testAmbiguousChoiceFromChoicelist() { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The provided answer is ambiguous. Value should be one of "env_2" or "env_3".'); $possibleChoices = [ 'env_1' => 'My first environment', 'env_2' => 'My environment', @@ -692,10 +690,13 @@ public function testAmbiguousChoiceFromChoicelist() $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices); $question->setMaxAttempts(1); + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The provided answer is ambiguous. Value should be one of "env_2" or "env_3".'); + $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("My environment\n")), $this->createOutputInterface(), $question); } - public static function answerProvider() + public static function answerProvider(): array { return [ ['env_1', 'env_1'], @@ -743,22 +744,18 @@ public function testAskThrowsExceptionOnMissingInput() { $this->expectException(MissingInputException::class); $this->expectExceptionMessage('Aborted.'); - $dialog = new QuestionHelper(); - $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new Question('What\'s your name?')); + (new QuestionHelper())->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new Question('What\'s your name?')); } public function testAskThrowsExceptionOnMissingInputForChoiceQuestion() { $this->expectException(MissingInputException::class); $this->expectExceptionMessage('Aborted.'); - $dialog = new QuestionHelper(); - $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new ChoiceQuestion('Choice', ['a', 'b'])); + (new QuestionHelper())->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new ChoiceQuestion('Choice', ['a', 'b'])); } public function testAskThrowsExceptionOnMissingInputWithValidator() { - $this->expectException(MissingInputException::class); - $this->expectExceptionMessage('Aborted.'); $dialog = new QuestionHelper(); $question = new Question('What\'s your name?'); @@ -768,6 +765,9 @@ public function testAskThrowsExceptionOnMissingInputWithValidator() } }); + $this->expectException(MissingInputException::class); + $this->expectExceptionMessage('Aborted.'); + $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), $question); } diff --git a/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php b/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php index 2af0b199c07f0..6cf79965bba7e 100644 --- a/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php @@ -137,8 +137,7 @@ public function testAskThrowsExceptionOnMissingInput() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Aborted.'); - $dialog = new SymfonyQuestionHelper(); - $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new Question('What\'s your name?')); + (new SymfonyQuestionHelper())->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new Question('What\'s your name?')); } public function testChoiceQuestionPadding() diff --git a/src/Symfony/Component/Console/Tests/Helper/TableStyleTest.php b/src/Symfony/Component/Console/Tests/Helper/TableStyleTest.php index 5ff28f19f4da2..dd740421f6a22 100644 --- a/src/Symfony/Component/Console/Tests/Helper/TableStyleTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/TableStyleTest.php @@ -20,7 +20,6 @@ public function testSetPadTypeWithInvalidType() { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Invalid padding type. Expected one of (STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH).'); - $style = new TableStyle(); - $style->setPadType(31); + (new TableStyle())->setPadType(31); } } diff --git a/src/Symfony/Component/Console/Tests/Helper/TableTest.php b/src/Symfony/Component/Console/Tests/Helper/TableTest.php index 2411a6fb4f0b9..728ea847f031f 100644 --- a/src/Symfony/Component/Console/Tests/Helper/TableTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/TableTest.php @@ -1017,16 +1017,15 @@ public function testColumnStyle() public function testThrowsWhenTheCellInAnArray() { - $table = new Table($this->getOutputStream()); + $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 ->setHeaders(['ISBN', 'Title', 'Author', 'Price']) ->setRows([ ['99921-58-10-7', [], 'Dante Alighieri', '9.95'], ]); - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('A cell must be a TableCell, a scalar or an object implementing "__toString()", "array" given.'); - $table->render(); } diff --git a/src/Symfony/Component/Console/Tests/Input/ArgvInputTest.php b/src/Symfony/Component/Console/Tests/Input/ArgvInputTest.php index 920dc492c4944..a47d557b78cd9 100644 --- a/src/Symfony/Component/Console/Tests/Input/ArgvInputTest.php +++ b/src/Symfony/Component/Console/Tests/Input/ArgvInputTest.php @@ -242,8 +242,7 @@ public function testInvalidInput($argv, $definition, $expectedExceptionMessage) $this->expectException(\RuntimeException::class); $this->expectExceptionMessage($expectedExceptionMessage); - $input = new ArgvInput($argv); - $input->bind($definition); + (new ArgvInput($argv))->bind($definition); } /** @@ -254,11 +253,10 @@ public function testInvalidInputNegatable($argv, $definition, $expectedException $this->expectException(\RuntimeException::class); $this->expectExceptionMessage($expectedExceptionMessage); - $input = new ArgvInput($argv); - $input->bind($definition); + (new ArgvInput($argv))->bind($definition); } - public static function provideInvalidInput() + public static function provideInvalidInput(): array { return [ [ @@ -329,7 +327,7 @@ public static function provideInvalidInput() ]; } - public static function provideInvalidNegatableInput() + public static function provideInvalidNegatableInput(): array { return [ [ diff --git a/src/Symfony/Component/Console/Tests/Input/ArrayInputTest.php b/src/Symfony/Component/Console/Tests/Input/ArrayInputTest.php index 733322490d00b..d6fe32bb3ab3e 100644 --- a/src/Symfony/Component/Console/Tests/Input/ArrayInputTest.php +++ b/src/Symfony/Component/Console/Tests/Input/ArrayInputTest.php @@ -74,7 +74,7 @@ public function testParseOptions($input, $options, $expectedOptions, $message) $this->assertEquals($expectedOptions, $input->getOptions(), $message); } - public static function provideOptions() + public static function provideOptions(): array { return [ [ @@ -133,7 +133,7 @@ public function testParseInvalidInput($parameters, $definition, $expectedExcepti new ArrayInput($parameters, $definition); } - public static function provideInvalidInput() + public static function provideInvalidInput(): array { return [ [ diff --git a/src/Symfony/Component/Console/Tests/Input/InputArgumentTest.php b/src/Symfony/Component/Console/Tests/Input/InputArgumentTest.php index 398048cbc592d..05447426cc468 100644 --- a/src/Symfony/Component/Console/Tests/Input/InputArgumentTest.php +++ b/src/Symfony/Component/Console/Tests/Input/InputArgumentTest.php @@ -86,25 +86,31 @@ public function testSetDefault() public function testSetDefaultWithRequiredArgument() { + $argument = new InputArgument('foo', InputArgument::REQUIRED); + $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot set a default value except for InputArgument::OPTIONAL mode.'); - $argument = new InputArgument('foo', InputArgument::REQUIRED); + $argument->setDefault('default'); } public function testSetDefaultWithRequiredArrayArgument() { + $argument = new InputArgument('foo', InputArgument::REQUIRED | InputArgument::IS_ARRAY); + $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot set a default value except for InputArgument::OPTIONAL mode.'); - $argument = new InputArgument('foo', InputArgument::REQUIRED | InputArgument::IS_ARRAY); + $argument->setDefault([]); } public function testSetDefaultWithArrayArgument() { + $argument = new InputArgument('foo', InputArgument::IS_ARRAY); + $this->expectException(\LogicException::class); $this->expectExceptionMessage('A default value for an array argument must be an array.'); - $argument = new InputArgument('foo', InputArgument::IS_ARRAY); + $argument->setDefault('default'); } @@ -130,10 +136,11 @@ public function testCompleteClosure() public function testCompleteClosureReturnIncorrectType() { + $argument = new InputArgument('foo', InputArgument::OPTIONAL, '', null, fn (CompletionInput $input) => 'invalid'); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Closure for argument "foo" must return an array. Got "string".'); - $argument = new InputArgument('foo', InputArgument::OPTIONAL, '', null, fn (CompletionInput $input) => 'invalid'); $argument->complete(new CompletionInput(), new CompletionSuggestions()); } } diff --git a/src/Symfony/Component/Console/Tests/Input/InputOptionTest.php b/src/Symfony/Component/Console/Tests/Input/InputOptionTest.php index 0b5271b324aea..74bf69586fa89 100644 --- a/src/Symfony/Component/Console/Tests/Input/InputOptionTest.php +++ b/src/Symfony/Component/Console/Tests/Input/InputOptionTest.php @@ -162,17 +162,21 @@ public function testSetDefault() public function testDefaultValueWithValueNoneMode() { + $option = new InputOption('foo', 'f', InputOption::VALUE_NONE); + $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot set a default value when using InputOption::VALUE_NONE mode.'); - $option = new InputOption('foo', 'f', InputOption::VALUE_NONE); + $option->setDefault('default'); } public function testDefaultValueWithIsArrayMode() { + $option = new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY); + $this->expectException(\LogicException::class); $this->expectExceptionMessage('A default value for an array option must be an array.'); - $option = new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY); + $option->setDefault('default'); } @@ -229,10 +233,11 @@ public function testCompleteClosure() public function testCompleteClosureReturnIncorrectType() { + $option = new InputOption('foo', null, InputOption::VALUE_OPTIONAL, '', null, fn (CompletionInput $input) => 'invalid'); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Closure for option "foo" must return an array. Got "string".'); - $option = new InputOption('foo', null, InputOption::VALUE_OPTIONAL, '', null, fn (CompletionInput $input) => 'invalid'); $option->complete(new CompletionInput(), new CompletionSuggestions()); } } diff --git a/src/Symfony/Component/Console/Tests/Input/InputTest.php b/src/Symfony/Component/Console/Tests/Input/InputTest.php index 6547822fbbced..34fb4833bb962 100644 --- a/src/Symfony/Component/Console/Tests/Input/InputTest.php +++ b/src/Symfony/Component/Console/Tests/Input/InputTest.php @@ -63,17 +63,21 @@ public function testOptions() public function testSetInvalidOption() { + $input = new ArrayInput(['--name' => 'foo'], new InputDefinition([new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default')])); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('The "foo" option does not exist.'); - $input = new ArrayInput(['--name' => 'foo'], new InputDefinition([new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default')])); + $input->setOption('foo', 'bar'); } public function testGetInvalidOption() { + $input = new ArrayInput(['--name' => 'foo'], new InputDefinition([new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default')])); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('The "foo" option does not exist.'); - $input = new ArrayInput(['--name' => 'foo'], new InputDefinition([new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default')])); + $input->getOption('foo'); } @@ -93,35 +97,43 @@ public function testArguments() public function testSetInvalidArgument() { + $input = new ArrayInput(['name' => 'foo'], new InputDefinition([new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default')])); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('The "foo" argument does not exist.'); - $input = new ArrayInput(['name' => 'foo'], new InputDefinition([new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default')])); + $input->setArgument('foo', 'bar'); } public function testGetInvalidArgument() { + $input = new ArrayInput(['name' => 'foo'], new InputDefinition([new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default')])); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('The "foo" argument does not exist.'); - $input = new ArrayInput(['name' => 'foo'], new InputDefinition([new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default')])); + $input->getArgument('foo'); } public function testValidateWithMissingArguments() { - $this->expectException(\RuntimeException::class); - $this->expectExceptionMessage('Not enough arguments (missing: "name").'); $input = new ArrayInput([]); $input->bind(new InputDefinition([new InputArgument('name', InputArgument::REQUIRED)])); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Not enough arguments (missing: "name").'); + $input->validate(); } public function testValidateWithMissingRequiredArguments() { - $this->expectException(\RuntimeException::class); - $this->expectExceptionMessage('Not enough arguments (missing: "name").'); $input = new ArrayInput(['bar' => 'baz']); $input->bind(new InputDefinition([new InputArgument('name', InputArgument::REQUIRED), new InputArgument('bar', InputArgument::OPTIONAL)])); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Not enough arguments (missing: "name").'); + $input->validate(); } diff --git a/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php b/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php index 41205d793619c..43d779631aa6f 100644 --- a/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php +++ b/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php @@ -137,8 +137,7 @@ public static function provideLevelsAndMessages() public function testThrowsOnInvalidLevel() { $this->expectException(InvalidArgumentException::class); - $logger = $this->getLogger(); - $logger->log('invalid level', 'Foo'); + $this->getLogger()->log('invalid level', 'Foo'); } public function testContextReplacement() diff --git a/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php b/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php index 3fec7df2d5123..ce0a24b99fda3 100644 --- a/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php +++ b/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php @@ -154,8 +154,6 @@ public function testCommandWithDefaultInputs() public function testCommandWithWrongInputsNumber() { - $this->expectException(\RuntimeException::class); - $this->expectExceptionMessage('Aborted.'); $questions = [ 'What\'s your name?', 'How are you?', @@ -174,13 +172,15 @@ public function testCommandWithWrongInputsNumber() $tester = new CommandTester($command); $tester->setInputs(['a', 'Bobby', 'Fine']); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Aborted.'); + $tester->execute([]); } public function testCommandWithQuestionsButNoInputs() { - $this->expectException(\RuntimeException::class); - $this->expectExceptionMessage('Aborted.'); $questions = [ 'What\'s your name?', 'How are you?', @@ -198,6 +198,10 @@ public function testCommandWithQuestionsButNoInputs() }); $tester = new CommandTester($command); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Aborted.'); + $tester->execute([]); } diff --git a/src/Symfony/Component/CssSelector/Tests/CssSelectorConverterTest.php b/src/Symfony/Component/CssSelector/Tests/CssSelectorConverterTest.php index 36d39f39d7cd5..c197032e5a817 100644 --- a/src/Symfony/Component/CssSelector/Tests/CssSelectorConverterTest.php +++ b/src/Symfony/Component/CssSelector/Tests/CssSelectorConverterTest.php @@ -48,8 +48,7 @@ public function testParseExceptions() { $this->expectException(ParseException::class); $this->expectExceptionMessage('Expected identifier, but found.'); - $converter = new CssSelectorConverter(); - $converter->toXPath('h1:'); + (new CssSelectorConverter())->toXPath('h1:'); } /** @dataProvider getCssToXPathWithoutPrefixTestData */ @@ -60,7 +59,7 @@ public function testCssToXPathWithoutPrefix($css, $xpath) $this->assertEquals($xpath, $converter->toXPath($css, ''), '->parse() parses an input string and returns a node'); } - public static function getCssToXPathWithoutPrefixTestData() + public static function getCssToXPathWithoutPrefixTestData(): array { return [ ['h1', 'h1'], diff --git a/src/Symfony/Component/CssSelector/Tests/Parser/TokenStreamTest.php b/src/Symfony/Component/CssSelector/Tests/Parser/TokenStreamTest.php index f50c8de8d00e7..3692854c67ac5 100644 --- a/src/Symfony/Component/CssSelector/Tests/Parser/TokenStreamTest.php +++ b/src/Symfony/Component/CssSelector/Tests/Parser/TokenStreamTest.php @@ -54,10 +54,11 @@ public function testGetNextIdentifier() public function testFailToGetNextIdentifier() { - $this->expectException(SyntaxErrorException::class); - $stream = new TokenStream(); $stream->push(new Token(Token::TYPE_DELIMITER, '.', 2)); + + $this->expectException(SyntaxErrorException::class); + $stream->getNextIdentifier(); } @@ -74,10 +75,11 @@ public function testGetNextIdentifierOrStar() public function testFailToGetNextIdentifierOrStar() { - $this->expectException(SyntaxErrorException::class); - $stream = new TokenStream(); $stream->push(new Token(Token::TYPE_DELIMITER, '.', 2)); + + $this->expectException(SyntaxErrorException::class); + $stream->getNextIdentifierOrStar(); } diff --git a/src/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.php b/src/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.php index bfb90728bee29..c161b802360de 100644 --- a/src/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.php +++ b/src/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.php @@ -38,56 +38,68 @@ public function testCssToXPath($css, $xpath) public function testCssToXPathPseudoElement() { - $this->expectException(ExpressionErrorException::class); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); + + $this->expectException(ExpressionErrorException::class); + $translator->cssToXPath('e::first-line'); } public function testGetExtensionNotExistsExtension() { - $this->expectException(ExpressionErrorException::class); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); + + $this->expectException(ExpressionErrorException::class); + $translator->getExtension('fake'); } public function testAddCombinationNotExistsExtension() { - $this->expectException(ExpressionErrorException::class); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $parser = new Parser(); $xpath = $parser->parse('*')[0]; $combinedXpath = $parser->parse('*')[0]; + + $this->expectException(ExpressionErrorException::class); + $translator->addCombination('fake', $xpath, $combinedXpath); } public function testAddFunctionNotExistsFunction() { - $this->expectException(ExpressionErrorException::class); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $xpath = new XPathExpr(); $function = new FunctionNode(new ElementNode(), 'fake'); + + $this->expectException(ExpressionErrorException::class); + $translator->addFunction($xpath, $function); } public function testAddPseudoClassNotExistsClass() { - $this->expectException(ExpressionErrorException::class); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $xpath = new XPathExpr(); + + $this->expectException(ExpressionErrorException::class); + $translator->addPseudoClass($xpath, 'fake'); } public function testAddAttributeMatchingClassNotExistsClass() { - $this->expectException(ExpressionErrorException::class); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $xpath = new XPathExpr(); + + $this->expectException(ExpressionErrorException::class); + $translator->addAttributeMatching($xpath, '', '', ''); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/AliasTest.php b/src/Symfony/Component/DependencyInjection/Tests/AliasTest.php index 1fa639efdba05..b1c8a4dbd8378 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/AliasTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/AliasTest.php @@ -74,12 +74,14 @@ public function testReturnsCorrectDeprecation() */ public function testCannotDeprecateWithAnInvalidTemplate($message) { - $this->expectException(InvalidArgumentException::class); $def = new Alias('foo'); + + $this->expectException(InvalidArgumentException::class); + $def->setDeprecated('package', '1.1', $message); } - public static function invalidDeprecationMessageProvider() + public static function invalidDeprecationMessageProvider(): array { return [ "With \rs" => ["invalid \r message %alias_id%"], diff --git a/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php b/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php index 8340c3e63507d..39c96f8c55c5f 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php @@ -91,9 +91,10 @@ public function testSetArgument() public function testReplaceArgumentShouldRequireIntegerIndex() { - $this->expectException(\InvalidArgumentException::class); $def = new ChildDefinition('foo'); + $this->expectException(\InvalidArgumentException::class); + $def->replaceArgument('0', 'foo'); } @@ -118,12 +119,13 @@ public function testReplaceArgument() public function testGetArgumentShouldCheckBounds() { - $this->expectException(\OutOfBoundsException::class); $def = new ChildDefinition('foo'); $def->setArguments([0 => 'foo']); $def->replaceArgument(0, 'foo'); + $this->expectException(\OutOfBoundsException::class); + $def->getArgument(1); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AbstractRecursivePassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AbstractRecursivePassTest.php index 23c42d1306502..adfa4f16218c3 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AbstractRecursivePassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AbstractRecursivePassTest.php @@ -107,12 +107,12 @@ protected function processValue($value, $isRoot = false): mixed public function testGetConstructorDefinitionNoClass() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Invalid service "foo": the class is not set.'); - $container = new ContainerBuilder(); $container->register('foo'); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Invalid service "foo": the class is not set.'); + (new class() extends AbstractRecursivePass { protected function processValue($value, $isRoot = false): mixed { diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AliasDeprecatedPublicServicesPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AliasDeprecatedPublicServicesPassTest.php index 9baff5e6fe190..86da767d54fae 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AliasDeprecatedPublicServicesPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AliasDeprecatedPublicServicesPassTest.php @@ -47,14 +47,14 @@ public function testProcess() */ public function testProcessWithMissingAttribute(string $attribute, array $attributes) { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage(sprintf('The "%s" attribute is mandatory for the "container.private" tag on the "foo" service.', $attribute)); - $container = new ContainerBuilder(); $container ->register('foo') ->addTag('container.private', $attributes); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(sprintf('The "%s" attribute is mandatory for the "container.private" tag on the "foo" service.', $attribute)); + (new AliasDeprecatedPublicServicesPass())->process($container); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php index 26a0ed1555022..074a0893db6bc 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php @@ -21,19 +21,20 @@ class AutoAliasServicePassTest extends TestCase { public function testProcessWithMissingParameter() { - $this->expectException(ParameterNotFoundException::class); $container = new ContainerBuilder(); $container->register('example') ->addTag('auto_alias', ['format' => '%non_existing%.example']); $pass = new AutoAliasServicePass(); + + $this->expectException(ParameterNotFoundException::class); + $pass->process($container); } public function testProcessWithMissingFormat() { - $this->expectException(InvalidArgumentException::class); $container = new ContainerBuilder(); $container->register('example') @@ -41,6 +42,9 @@ public function testProcessWithMissingFormat() $container->setParameter('existing', 'mysql'); $pass = new AutoAliasServicePass(); + + $this->expectException(InvalidArgumentException::class); + $pass->process($container); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php index abc9406f5473b..fc8cba8e83cb6 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php @@ -609,13 +609,14 @@ public function testScalarArgsCannotBeAutowired() public function testUnionScalarArgsCannotBeAutowired() { - $this->expectException(AutowiringFailedException::class); - $this->expectExceptionMessage('Cannot autowire service "union_scalars": argument "$timeout" of method "Symfony\Component\DependencyInjection\Tests\Compiler\UnionScalars::__construct()" is type-hinted "float|int", you should configure its value explicitly.'); $container = new ContainerBuilder(); $container->register('union_scalars', UnionScalars::class) ->setAutowired(true); + $this->expectException(AutowiringFailedException::class); + $this->expectExceptionMessage('Cannot autowire service "union_scalars": argument "$timeout" of method "Symfony\Component\DependencyInjection\Tests\Compiler\UnionScalars::__construct()" is type-hinted "float|int", you should configure its value explicitly.'); + (new AutowirePass())->process($container); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.php index 960c6331e4f9f..c9bcb10878bec 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.php @@ -24,28 +24,29 @@ class CheckCircularReferencesPassTest extends TestCase { public function testProcess() { - $this->expectException(ServiceCircularReferenceException::class); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('a')); + $this->expectException(ServiceCircularReferenceException::class); + $this->process($container); } public function testProcessWithAliases() { - $this->expectException(ServiceCircularReferenceException::class); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->setAlias('b', 'c'); $container->setAlias('c', 'a'); + $this->expectException(ServiceCircularReferenceException::class); + $this->process($container); } public function testProcessWithFactory() { - $this->expectException(ServiceCircularReferenceException::class); $container = new ContainerBuilder(); $container @@ -56,23 +57,25 @@ public function testProcessWithFactory() ->register('b', 'stdClass') ->setFactory([new Reference('a'), 'getInstance']); + $this->expectException(ServiceCircularReferenceException::class); + $this->process($container); } public function testProcessDetectsIndirectCircularReference() { - $this->expectException(ServiceCircularReferenceException::class); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('c')); $container->register('c')->addArgument(new Reference('a')); + $this->expectException(ServiceCircularReferenceException::class); + $this->process($container); } public function testProcessDetectsIndirectCircularReferenceWithFactory() { - $this->expectException(ServiceCircularReferenceException::class); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); @@ -83,17 +86,20 @@ public function testProcessDetectsIndirectCircularReferenceWithFactory() $container->register('c')->addArgument(new Reference('a')); + $this->expectException(ServiceCircularReferenceException::class); + $this->process($container); } public function testDeepCircularReference() { - $this->expectException(ServiceCircularReferenceException::class); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('c')); $container->register('c')->addArgument(new Reference('b')); + $this->expectException(ServiceCircularReferenceException::class); + $this->process($container); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.php index 1cd0e0023d51d..634fc71377a98 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.php @@ -21,19 +21,21 @@ class CheckDefinitionValidityPassTest extends TestCase { public function testProcessDetectsSyntheticNonPublicDefinitions() { - $this->expectException(RuntimeException::class); $container = new ContainerBuilder(); $container->register('a')->setSynthetic(true)->setPublic(false); + $this->expectException(RuntimeException::class); + $this->process($container); } public function testProcessDetectsNonSyntheticNonAbstractDefinitionWithoutClass() { - $this->expectException(RuntimeException::class); $container = new ContainerBuilder(); $container->register('a')->setSynthetic(false)->setAbstract(false); + $this->expectException(RuntimeException::class); + $this->process($container); } @@ -92,10 +94,12 @@ public function testValidTags() */ public function testInvalidTags(string $name, array $attributes, string $message) { - $this->expectException(RuntimeException::class); $this->expectExceptionMessage($message); $container = new ContainerBuilder(); $container->register('a', 'class')->addTag($name, $attributes); + + $this->expectException(RuntimeException::class); + $this->process($container); } @@ -121,21 +125,23 @@ public static function provideInvalidTags(): iterable public function testDynamicPublicServiceName() { - $this->expectException(EnvParameterException::class); $container = new ContainerBuilder(); $env = $container->getParameterBag()->get('env(BAR)'); $container->register("foo.$env", 'class')->setPublic(true); + $this->expectException(EnvParameterException::class); + $this->process($container); } public function testDynamicPublicAliasName() { - $this->expectException(EnvParameterException::class); $container = new ContainerBuilder(); $env = $container->getParameterBag()->get('env(BAR)'); $container->setAlias("foo.$env", 'class')->setPublic(true); + $this->expectException(EnvParameterException::class); + $this->process($container); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php index 2fd831ecc5ee0..bce8103649aa4 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php @@ -41,7 +41,6 @@ public function testProcess() public function testProcessThrowsExceptionOnInvalidReference() { - $this->expectException(ServiceNotFoundException::class); $container = new ContainerBuilder(); $container @@ -49,12 +48,13 @@ public function testProcessThrowsExceptionOnInvalidReference() ->addArgument(new Reference('b')) ; + $this->expectException(ServiceNotFoundException::class); + $this->process($container); } public function testProcessThrowsExceptionOnInvalidReferenceFromInlinedDefinition() { - $this->expectException(ServiceNotFoundException::class); $container = new ContainerBuilder(); $def = new Definition(); @@ -65,6 +65,8 @@ public function testProcessThrowsExceptionOnInvalidReferenceFromInlinedDefinitio ->addArgument($def) ; + $this->expectException(ServiceNotFoundException::class); + $this->process($container); } @@ -84,34 +86,36 @@ public function testProcessDefinitionWithBindings() public function testWithErroredServiceLocator() { - $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(); ServiceLocatorTagPass::register($container, ['foo' => new Reference('baz')], 'bar'); (new AnalyzeServiceReferencesPass())->process($container); (new InlineServiceDefinitionsPass())->process($container); + + $this->expectException(ServiceNotFoundException::class); + $this->expectExceptionMessage('The service "foo" in the container provided to "bar" has a dependency on a non-existent service "baz".'); + $this->process($container); } public function testWithErroredHiddenService() { - $this->expectException(ServiceNotFoundException::class); - $this->expectExceptionMessage('The service "bar" has a dependency on a non-existent service "foo".'); $container = new ContainerBuilder(); ServiceLocatorTagPass::register($container, ['foo' => new Reference('foo')], 'bar'); (new AnalyzeServiceReferencesPass())->process($container); (new InlineServiceDefinitionsPass())->process($container); + + $this->expectException(ServiceNotFoundException::class); + $this->expectExceptionMessage('The service "bar" has a dependency on a non-existent service "foo".'); + $this->process($container); } public function testProcessThrowsExceptionOnInvalidReferenceWithAlternatives() { - $this->expectException(ServiceNotFoundException::class); - $this->expectExceptionMessage('The service "a" has a dependency on a non-existent service "@ccc". Did you mean this: "ccc"?'); $container = new ContainerBuilder(); $container @@ -121,19 +125,22 @@ public function testProcessThrowsExceptionOnInvalidReferenceWithAlternatives() $container ->register('ccc', '\stdClass'); + $this->expectException(ServiceNotFoundException::class); + $this->expectExceptionMessage('The service "a" has a dependency on a non-existent service "@ccc". Did you mean this: "ccc"?'); + $this->process($container); } public function testCurrentIdIsExcludedFromAlternatives() { - $this->expectException(ServiceNotFoundException::class); - $this->expectExceptionMessage('The service "app.my_service" has a dependency on a non-existent service "app.my_service2".'); - $container = new ContainerBuilder(); $container ->register('app.my_service', \stdClass::class) ->addArgument(new Reference('app.my_service2')); + $this->expectException(ServiceNotFoundException::class); + $this->expectExceptionMessage('The service "app.my_service" has a dependency on a non-existent service "app.my_service2".'); + $this->process($container); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckReferenceValidityPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckReferenceValidityPassTest.php index 2c0c5e04675b7..1589e3da8aa72 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckReferenceValidityPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckReferenceValidityPassTest.php @@ -20,12 +20,13 @@ class CheckReferenceValidityPassTest extends TestCase { public function testProcessDetectsReferenceToAbstractDefinition() { - $this->expectException(\RuntimeException::class); $container = new ContainerBuilder(); $container->register('a')->setAbstract(true); $container->register('b')->addArgument(new Reference('a')); + $this->expectException(\RuntimeException::class); + $this->process($container); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckTypeDeclarationsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckTypeDeclarationsPassTest.php index cb1bf1af89063..d8951e613923d 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckTypeDeclarationsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckTypeDeclarationsPassTest.php @@ -46,54 +46,54 @@ class CheckTypeDeclarationsPassTest extends TestCase { public function testProcessThrowsExceptionOnInvalidTypesConstructorArguments() { - $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(); $container->register('foo', Foo::class); $container->register('bar', Bar::class) ->addArgument(new Reference('foo')); + $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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } public function testProcessThrowsExceptionOnInvalidTypesMethodCallArguments() { - $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(); $container->register('foo', Foo::class); $container->register('bar', BarMethodCall::class) ->addMethodCall('setFoo', [new Reference('foo')]); + $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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } public function testProcessFailsWhenPassingNullToRequiredArgument() { - $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(); $container->register('bar', Bar::class) ->addArgument(null); + $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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } public function testProcessThrowsExceptionWhenMissingArgumentsInConstructor() { - $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(); $container->register('bar', Bar::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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } @@ -124,9 +124,6 @@ public function testProcessRegisterWithClassName() public function testProcessThrowsExceptionWhenMissingArgumentsInMethodCall() { - $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(); $container->register('foo', \stdClass::class); @@ -134,14 +131,14 @@ public function testProcessThrowsExceptionWhenMissingArgumentsInMethodCall() ->addArgument(new Reference('foo')) ->addMethodCall('setFoo', []); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid definition for service "bar": "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\BarMethodCall::setFoo()" requires 1 arguments, 0 passed.'); + (new CheckTypeDeclarationsPass(true))->process($container); } public function testProcessVariadicFails() { - $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(); $container->register('stdClass', \stdClass::class); @@ -153,14 +150,14 @@ public function testProcessVariadicFails() new Reference('stdClass'), ]); + $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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } public function testProcessVariadicFailsOnPassingBadTypeOnAnotherArgument() { - $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(); $container->register('stdClass', \stdClass::class); @@ -169,6 +166,9 @@ public function testProcessVariadicFailsOnPassingBadTypeOnAnotherArgument() new Reference('stdClass'), ]); + $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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } @@ -222,9 +222,6 @@ public function testProcessSuccessWhenUsingOptionalArgumentWithGoodType() public function testProcessFailsWhenUsingOptionalArgumentWithBadType() { - $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(); $container->register('stdClass', \stdClass::class); @@ -235,6 +232,9 @@ public function testProcessFailsWhenUsingOptionalArgumentWithBadType() new Reference('stdClass'), ]); + $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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } @@ -252,14 +252,14 @@ public function testProcessSuccessWhenPassingNullToOptional() public function testProcessSuccessWhenPassingNullToOptionalThatDoesNotAcceptNull() { - $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(); $container->register('bar', BarOptionalArgumentNotNull::class) ->addArgument(null); + $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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } @@ -293,22 +293,19 @@ public function testProcessSuccessScalarType() public function testProcessFailsOnPassingScalarTypeToConstructorTypedWithClass() { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Bar::__construct()" accepts "stdClass", "int" passed.'); - $container = new ContainerBuilder(); $container->register('bar', Bar::class) ->addArgument(1); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CheckTypeDeclarationsPass\\Bar::__construct()" accepts "stdClass", "int" passed.'); + (new CheckTypeDeclarationsPass(true))->process($container); } public function testProcessFailsOnPassingScalarTypeToMethodTypedWithClass() { - $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(); $container->register('bar', BarMethodCall::class) @@ -316,14 +313,14 @@ public function testProcessFailsOnPassingScalarTypeToMethodTypedWithClass() 'builtin type instead of 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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } public function testProcessFailsOnPassingClassToScalarTypedParameter() { - $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(); $container->register('foo', Foo::class); @@ -333,6 +330,9 @@ public function testProcessFailsOnPassingClassToScalarTypedParameter() new Reference('foo'), ]); + $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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } @@ -381,14 +381,14 @@ public function testProcessSuccessWhenPassingArray() public function testProcessSuccessWhenPassingIntegerToArrayTypedParameter() { - $this->expectException(InvalidParameterTypeException::class); - $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\Component\DependencyInjection\Tests\Fixtures\CheckTypeDeclarationsPass\BarMethodCall::setArray()" accepts "array", "int" passed.'); - $container = new ContainerBuilder(); $container->register('bar', BarMethodCall::class) ->addMethodCall('setArray', [1]); + $this->expectException(InvalidParameterTypeException::class); + $this->expectExceptionMessage('Invalid definition for service "bar": argument 1 of "Symfony\Component\DependencyInjection\Tests\Fixtures\CheckTypeDeclarationsPass\BarMethodCall::setArray()" accepts "array", "int" passed.'); + (new CheckTypeDeclarationsPass(true))->process($container); } @@ -438,9 +438,6 @@ public function testProcessFactory() public function testProcessFactoryFailsOnInvalidParameterType() { - $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(); $container->register('foo', Foo::class); @@ -451,14 +448,14 @@ public function testProcessFactoryFailsOnInvalidParameterType() 'createBarArguments', ]); + $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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } public function testProcessFactoryFailsOnInvalidParameterTypeOptional() { - $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(); $container->register('stdClass', \stdClass::class); @@ -471,6 +468,9 @@ public function testProcessFactoryFailsOnInvalidParameterTypeOptional() 'createBarArguments', ]); + $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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } @@ -644,9 +644,6 @@ public function testProcessSuccessWhenExpressionReturnsObject() public function testProcessHandleMixedEnvPlaceholder() { - $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([ 'ccc' => '%env(FOO)%', ])); @@ -655,14 +652,14 @@ public function testProcessHandleMixedEnvPlaceholder() ->register('foobar', BarMethodCall::class) ->addMethodCall('setArray', ['foo%ccc%']); + $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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } public function testProcessHandleMultipleEnvPlaceholder() { - $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([ 'ccc' => '%env(FOO)%', 'fcy' => '%env(int:BAR)%', @@ -672,6 +669,9 @@ public function testProcessHandleMultipleEnvPlaceholder() ->register('foobar', BarMethodCall::class) ->addMethodCall('setArray', ['%ccc%%fcy%']); + $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.'); + (new CheckTypeDeclarationsPass(true))->process($container); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php b/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php index fd1ec64514e04..85693bec0b27c 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php @@ -241,8 +241,7 @@ public function testGetThrowsExceptionIfServiceDoesNotExist() { $this->expectException(ServiceNotFoundException::class); $this->expectExceptionMessage('You have requested a non-existent service "foo".'); - $builder = new ContainerBuilder(); - $builder->get('foo'); + (new ContainerBuilder())->get('foo'); } public function testGetReturnsNullIfServiceDoesNotExistAndInvalidReferenceIsUsed() @@ -254,9 +253,11 @@ public function testGetReturnsNullIfServiceDoesNotExistAndInvalidReferenceIsUsed public function testGetThrowsCircularReferenceExceptionIfServiceHasReferenceToItself() { - $this->expectException(ServiceCircularReferenceException::class); $builder = new ContainerBuilder(); $builder->register('baz', 'stdClass')->setArguments([new Reference('baz')]); + + $this->expectException(ServiceCircularReferenceException::class); + $builder->get('baz'); } @@ -307,8 +308,7 @@ public function testNonSharedServicesReturnsDifferentInstances() public function testBadAliasId($id) { $this->expectException(InvalidArgumentException::class); - $builder = new ContainerBuilder(); - $builder->setAlias($id, 'foo'); + (new ContainerBuilder())->setAlias($id, 'foo'); } /** @@ -317,11 +317,10 @@ public function testBadAliasId($id) public function testBadDefinitionId($id) { $this->expectException(InvalidArgumentException::class); - $builder = new ContainerBuilder(); - $builder->setDefinition($id, new Definition('Foo')); + (new ContainerBuilder())->setDefinition($id, new Definition('Foo')); } - public static function provideBadId() + public static function provideBadId(): array { return [ [''], @@ -643,9 +642,11 @@ public function testCreateServiceWithIteratorArgument() public function testCreateSyntheticService() { - $this->expectException(\RuntimeException::class); $builder = new ContainerBuilder(); $builder->register('foo', 'Bar\FooClass')->setSynthetic(true); + + $this->expectException(\RuntimeException::class); + $builder->get('foo'); } @@ -690,9 +691,6 @@ public function testGetEnvCountersWithEnum() public function testCreateServiceWithAbstractArgument() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Argument "$baz" of service "foo" is abstract: should be defined by Pass.'); - $builder = new ContainerBuilder(); $builder->register('foo', FooWithAbstractArgument::class) ->setArgument('$baz', new AbstractArgument('should be defined by Pass')) @@ -700,6 +698,9 @@ public function testCreateServiceWithAbstractArgument() $builder->compile(); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Argument "$baz" of service "foo" is abstract: should be defined by Pass.'); + $builder->get('foo'); } @@ -714,13 +715,14 @@ public function testResolveServices() public function testResolveServicesWithDecoratedDefinition() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Constructing service "foo" from a parent definition is not supported at build time.'); $builder = new ContainerBuilder(); $builder->setDefinition('grandpa', new Definition('stdClass')); $builder->setDefinition('parent', new ChildDefinition('grandpa')); $builder->setDefinition('foo', new ChildDefinition('parent')); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Constructing service "foo" from a parent definition is not supported at build time.'); + $builder->get('foo'); } @@ -808,12 +810,14 @@ public function testMergeWithExcludedServices() public function testMergeThrowsExceptionForDuplicateAutomaticInstanceofDefinitions() { - $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(); $container->registerForAutoconfiguration('AInterface'); $config->registerForAutoconfiguration('AInterface'); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"AInterface" has already been autoconfigured and merge() does not support merging autoconfiguration for the same class/interface.'); + $container->merge($config); } @@ -913,12 +917,14 @@ public function testCompileWithArrayAndAnotherResolveEnv() public function testCompileWithArrayInStringResolveEnv() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('A string value must be composed of strings and/or numbers, but found parameter "env(json:ARRAY)" of type "array" inside string value "ABC %env(json:ARRAY)%".'); putenv('ARRAY={"foo":"bar"}'); $container = new ContainerBuilder(); $container->setParameter('foo', 'ABC %env(json:ARRAY)%'); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('A string value must be composed of strings and/or numbers, but found parameter "env(json:ARRAY)" of type "array" inside string value "ABC %env(json:ARRAY)%".'); + $container->compile(true); putenv('ARRAY'); @@ -926,10 +932,12 @@ public function testCompileWithArrayInStringResolveEnv() public function testCompileWithResolveMissingEnv() { - $this->expectException(EnvNotFoundException::class); - $this->expectExceptionMessage('Environment variable not found: "FOO".'); $container = new ContainerBuilder(); $container->setParameter('foo', '%env(FOO)%'); + + $this->expectException(EnvNotFoundException::class); + $this->expectExceptionMessage('Environment variable not found: "FOO".'); + $container->compile(true); } @@ -1037,10 +1045,12 @@ public function testCircularDynamicEnv() public function testMergeLogicException() { - $this->expectException(\LogicException::class); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->compile(); + + $this->expectException(\LogicException::class); + $container->merge(new ContainerBuilder()); } @@ -1272,11 +1282,13 @@ public function testPrivateServiceUser() public function testThrowsExceptionWhenSetServiceOnACompiledContainer() { - $this->expectException(\BadMethodCallException::class); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->register('a', 'stdClass')->setPublic(true); $container->compile(); + + $this->expectException(\BadMethodCallException::class); + $container->set('a', new \stdClass()); } @@ -1301,10 +1313,12 @@ public function testNoExceptionWhenSetSyntheticServiceOnACompiledContainer() public function testThrowsExceptionWhenSetDefinitionOnACompiledContainer() { - $this->expectException(\BadMethodCallException::class); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->compile(); + + $this->expectException(\BadMethodCallException::class); + $container->setDefinition('a', new Definition()); } @@ -1394,8 +1408,6 @@ public function testInlinedDefinitions() public function testThrowsCircularExceptionForCircularAliases() { - $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(); $builder->setAliases([ @@ -1404,6 +1416,9 @@ public function testThrowsCircularExceptionForCircularAliases() 'App\\TestClass' => new Alias('app.test_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->findDefinition('foo'); } @@ -1450,59 +1465,64 @@ public function testClassFromId() public function testNoClassFromGlobalNamespaceClassId() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('The definition for "DateTimeImmutable" has no class attribute, and appears to reference a class or interface in the global namespace.'); $container = new ContainerBuilder(); $container->register(\DateTimeImmutable::class); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The definition for "DateTimeImmutable" has no class attribute, and appears to reference a class or interface in the global namespace.'); + $container->compile(); } public function testNoClassFromGlobalNamespaceClassIdWithLeadingSlash() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('The definition for "\DateTimeImmutable" has no class attribute, and appears to reference a class or interface in the global namespace.'); $container = new ContainerBuilder(); $container->register('\\'.\DateTimeImmutable::class); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The definition for "\DateTimeImmutable" has no class attribute, and appears to reference a class or interface in the global namespace.'); + $container->compile(); } public function testNoClassFromNamespaceClassIdWithLeadingSlash() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('The definition for "\Symfony\Component\DependencyInjection\Tests\FooClass" has no class attribute, and appears to reference a class or interface. Please specify the class attribute explicitly or remove the leading backslash by renaming the service to "Symfony\Component\DependencyInjection\Tests\FooClass" to get rid of this error.'); $container = new ContainerBuilder(); $container->register('\\'.FooClass::class); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The definition for "\Symfony\Component\DependencyInjection\Tests\FooClass" has no class attribute, and appears to reference a class or interface. Please specify the class attribute explicitly or remove the leading backslash by renaming the service to "Symfony\Component\DependencyInjection\Tests\FooClass" to get rid of this error.'); + $container->compile(); } public function testNoClassFromNonClassId() { + $container = new ContainerBuilder(); + $container->register('123_abc'); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The definition for "123_abc" has no class.'); - $container = new ContainerBuilder(); - $container->register('123_abc'); $container->compile(); } public function testNoClassFromNsSeparatorId() { + $container = new ContainerBuilder(); + $container->register('\\foo'); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The definition for "\foo" has no class.'); - $container = new ContainerBuilder(); - $container->register('\\foo'); $container->compile(); } public function testGetThrownServiceNotFoundExceptionWithCorrectServiceId() { - $this->expectException(ServiceNotFoundException::class); - $this->expectExceptionMessage('The service "child_service" has a dependency on a non-existent service "non_existent_service".'); - $container = new ContainerBuilder(); $container->register('child_service', \stdClass::class) ->addArgument([ @@ -1516,6 +1536,9 @@ public function testGetThrownServiceNotFoundExceptionWithCorrectServiceId() ]) ; + $this->expectException(ServiceNotFoundException::class); + $this->expectExceptionMessage('The service "child_service" has a dependency on a non-existent service "non_existent_service".'); + $container->compile(); } @@ -1753,14 +1776,15 @@ public function testIdCanBeAnObjectAsLongAsItCanBeCastToString() public function testErroredDefinition() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Service "errored_definition" is broken.'); $container = new ContainerBuilder(); $container->register('errored_definition', 'stdClass') ->addError('Service "errored_definition" is broken.') ->setPublic(true); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Service "errored_definition" is broken.'); + $container->get('errored_definition'); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php b/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php index f768e702eec8d..ccec9839e4e9f 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php @@ -264,21 +264,25 @@ public function testGetCircularReference() public function testGetSyntheticServiceThrows() { - $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'; $container = new \ProjectServiceContainer(); + + $this->expectException(ServiceNotFoundException::class); + $this->expectExceptionMessage('The "request" service is synthetic, it needs to be set at boot time before it can be used.'); + $container->get('request'); } public function testGetRemovedServiceThrows() { - $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'; $container = new \ProjectServiceContainer(); + + $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.'); + $container->get('inlined'); } @@ -400,10 +404,12 @@ public function testCheckExistenceOfAnInternalPrivateService() public function testRequestAnInternalSharedPrivateService() { - $this->expectException(ServiceNotFoundException::class); - $this->expectExceptionMessage('You have requested a non-existent service "internal".'); $c = new ProjectServiceContainer(); $c->get('internal_dependency'); + + $this->expectException(ServiceNotFoundException::class); + $this->expectExceptionMessage('You have requested a non-existent service "internal".'); + $c->get('internal'); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/DefinitionTest.php b/src/Symfony/Component/DependencyInjection/Tests/DefinitionTest.php index 783a3cf5f015a..8f33418671f63 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/DefinitionTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/DefinitionTest.php @@ -118,9 +118,11 @@ public function testMethodCalls() public function testExceptionOnEmptyMethodCall() { + $def = new Definition('stdClass'); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Method name cannot be empty.'); - $def = new Definition('stdClass'); + $def->addMethodCall(''); } @@ -189,12 +191,14 @@ public function testSetIsDeprecated() */ public function testSetDeprecatedWithInvalidDeprecationTemplate($message) { - $this->expectException(InvalidArgumentException::class); $def = new Definition('stdClass'); + + $this->expectException(InvalidArgumentException::class); + $def->setDeprecated('vendor/package', '1.1', $message); } - public static function invalidDeprecationMessageProvider() + public static function invalidDeprecationMessageProvider(): array { return [ "With \rs" => ["invalid \r message %service_id%"], @@ -274,28 +278,32 @@ public function testSetArgument() public function testGetArgumentShouldCheckBounds() { - $this->expectException(\OutOfBoundsException::class); $def = new Definition('stdClass'); - $def->addArgument('foo'); + + $this->expectException(\OutOfBoundsException::class); + $def->getArgument(1); } public function testReplaceArgumentShouldCheckBounds() { + $def = new Definition('stdClass'); + $def->addArgument('foo'); + $this->expectException(\OutOfBoundsException::class); $this->expectExceptionMessage('The index "1" is not in the range [0, 0] of the arguments of class "stdClass".'); - $def = new Definition('stdClass'); - $def->addArgument('foo'); $def->replaceArgument(1, 'bar'); } public function testReplaceArgumentWithoutExistingArgumentsShouldCheckBounds() { + $def = new Definition('stdClass'); + $this->expectException(\OutOfBoundsException::class); $this->expectExceptionMessage('Cannot replace arguments for class "stdClass" if none have been configured yet.'); - $def = new Definition('stdClass'); + $def->replaceArgument(0, 'bar'); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php b/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php index 8de0eaf8fc255..1b8dfdde6c5f1 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php @@ -196,9 +196,10 @@ public static function validInts() */ public function testGetEnvIntInvalid($value) { + $processor = new EnvVarProcessor(new Container()); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Non-numeric env var'); - $processor = new EnvVarProcessor(new Container()); $processor->getEnv('int', 'foo', function ($name) use ($value) { $this->assertSame('foo', $name); @@ -246,9 +247,10 @@ public static function validFloats() */ public function testGetEnvFloatInvalid($value) { + $processor = new EnvVarProcessor(new Container()); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Non-numeric env var'); - $processor = new EnvVarProcessor(new Container()); $processor->getEnv('float', 'foo', function ($name) use ($value) { $this->assertSame('foo', $name); @@ -295,9 +297,10 @@ public static function validConsts() */ public function testGetEnvConstInvalid($value) { + $processor = new EnvVarProcessor(new Container()); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('undefined constant'); - $processor = new EnvVarProcessor(new Container()); $processor->getEnv('const', 'foo', function ($name) use ($value) { $this->assertSame('foo', $name); @@ -373,9 +376,10 @@ public static function validJson() public function testGetEnvInvalidJson() { + $processor = new EnvVarProcessor(new Container()); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Syntax error'); - $processor = new EnvVarProcessor(new Container()); $processor->getEnv('json', 'foo', function ($name) { $this->assertSame('foo', $name); @@ -389,9 +393,10 @@ public function testGetEnvInvalidJson() */ public function testGetEnvJsonOther($value) { + $processor = new EnvVarProcessor(new Container()); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid JSON env var'); - $processor = new EnvVarProcessor(new Container()); $processor->getEnv('json', 'foo', function ($name) use ($value) { $this->assertSame('foo', $name); @@ -413,9 +418,10 @@ public static function otherJsonValues() public function testGetEnvUnknown() { + $processor = new EnvVarProcessor(new Container()); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Unsupported env var prefix'); - $processor = new EnvVarProcessor(new Container()); $processor->getEnv('unknown', 'foo', function ($name) { $this->assertSame('foo', $name); @@ -426,9 +432,10 @@ public function testGetEnvUnknown() public function testGetEnvKeyInvalidKey() { + $processor = new EnvVarProcessor(new Container()); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Invalid env "key:foo": a key specifier should be provided.'); - $processor = new EnvVarProcessor(new Container()); $processor->getEnv('key', 'foo', function ($name) { $this->fail('Should not get here'); @@ -440,9 +447,10 @@ public function testGetEnvKeyInvalidKey() */ public function testGetEnvKeyNoArrayResult($value) { + $processor = new EnvVarProcessor(new Container()); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Resolved value of "foo" did not result in an array value.'); - $processor = new EnvVarProcessor(new Container()); $processor->getEnv('key', 'index:foo', function ($name) use ($value) { $this->assertSame('foo', $name); @@ -466,9 +474,10 @@ public static function noArrayValues() */ public function testGetEnvKeyArrayKeyNotFound($value) { + $processor = new EnvVarProcessor(new Container()); + $this->expectException(EnvNotFoundException::class); $this->expectExceptionMessage('Key "index" not found in'); - $processor = new EnvVarProcessor(new Container()); $processor->getEnv('key', 'index:foo', function ($name) use ($value) { $this->assertSame('foo', $name); @@ -621,9 +630,10 @@ public static function validNullables() public function testRequireMissingFile() { + $processor = new EnvVarProcessor(new Container()); + $this->expectException(EnvNotFoundException::class); $this->expectExceptionMessage('missing-file'); - $processor = new EnvVarProcessor(new Container()); $processor->getEnv('require', '/missing-file', fn ($name) => $name); } @@ -684,15 +694,15 @@ public function testGetEnvResolveNoMatch() */ public function testGetEnvResolveNotScalar($value) { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Parameter "bar" found when resolving env var "foo" must be scalar'); - $container = new ContainerBuilder(); $container->setParameter('bar', $value); $container->compile(); $processor = new EnvVarProcessor($container); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Parameter "bar" found when resolving env var "foo" must be scalar'); + $processor->getEnv('resolve', 'foo', fn () => '%bar%'); } @@ -877,9 +887,10 @@ public function loadEnvVars(): array public function testGetEnvInvalidPrefixWithDefault() { + $processor = new EnvVarProcessor(new Container()); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Unsupported env var prefix'); - $processor = new EnvVarProcessor(new Container()); $processor->getEnv('unknown', 'default::FAKE', function ($name) { $this->assertSame('default::FAKE', $name); diff --git a/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php b/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php index 9e5e9d19b1429..96d16c40f2619 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php @@ -34,13 +34,14 @@ public function getServiceLocator(array $factories): ContainerInterface public function testGetThrowsOnUndefinedService() { - $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' => fn () => 'bar', 'bar' => fn () => 'baz', ]); + $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->get('dummy'); } @@ -53,26 +54,29 @@ public function testThrowsOnCircularReference() public function testThrowsInServiceSubscriber() { - $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()); $subscriber = new SomeServiceSubscriber(); $subscriber->container = $this->getServiceLocator(['bar' => function () {}]); $subscriber->container = $subscriber->container->withContext('caller', $container); + $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()".'); + $subscriber->getFoo(); } public function testGetThrowsServiceNotFoundException() { - $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()); $locator = new ServiceLocator([]); $locator = $locator->withContext('foo', $container); + + $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.'); + $locator->get('foo'); }