diff --git a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.php b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.php index ca75437b76..19c73804a8 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.php @@ -13,6 +13,7 @@ namespace Symfony\Bridge\Doctrine\Tests\DependencyInjection\CompilerPass; use PHPUnit\Framework\TestCase; use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; @@ -21,11 +22,11 @@ use Symfony\Component\DependencyInjection\ServiceLocator; class RegisterEventListenersAndSubscribersPassTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - */ + use ForwardCompatTestTrait; + public function testExceptionOnAbstractTaggedSubscriber() { + $this->expectException('InvalidArgumentException'); $container = $this->createBuilder(); $abstractDefinition = new Definition('stdClass'); @@ -37,11 +38,9 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase $this->process($container); } - /** - * @expectedException \InvalidArgumentException - */ public function testExceptionOnAbstractTaggedListener() { + $this->expectException('InvalidArgumentException'); $container = $this->createBuilder(); $abstractDefinition = new Definition('stdClass'); diff --git a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterMappingsPassTest.php b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterMappingsPassTest.php index 0bb2642a76..e6c06fd328 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterMappingsPassTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterMappingsPassTest.php @@ -4,17 +4,18 @@ namespace Symfony\Bridge\Doctrine\Tests\DependencyInjection\CompilerPass; use PHPUnit\Framework\TestCase; use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterMappingsPass; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; class RegisterMappingsPassTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageould Could not find the manager name parameter in the container. Tried the following parameter names: "manager.param.one", "manager.param.two" - */ + use ForwardCompatTestTrait; + public function testNoDriverParmeterException() { + $this->expectException('InvalidArgumentException'); + $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', diff --git a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php index d13aa4d0c4..d5a317f4ca 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php @@ -52,11 +52,9 @@ class DoctrineExtensionTest extends TestCase }); } - /** - * @expectedException \LogicException - */ public function testFixManagersAutoMappingsWithTwoAutomappings() { + $this->expectException('LogicException'); $emConfigs = [ 'em1' => [ 'auto_mapping' => true, @@ -237,12 +235,10 @@ class DoctrineExtensionTest extends TestCase $this->assertTrue($container->hasAlias('doctrine.orm.default_metadata_cache')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage "unrecognized_type" is an unrecognized Doctrine cache driver. - */ public function testUnrecognizedCacheDriverException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('"unrecognized_type" is an unrecognized Doctrine cache driver.'); $cacheName = 'metadata_cache'; $container = $this->createContainer(); $objectManager = [ diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php index ee22d9791f..22ed6b5521 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php @@ -378,12 +378,11 @@ class DoctrineChoiceLoaderTest extends TestCase $this->assertSame([$this->obj2], $loader->loadChoicesForValues(['2'], $value)); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The second argument `$idReader` of "Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader::__construct" must be null when the query cannot be optimized because of composite id fields. - */ public function testPassingIdReaderWithoutSingleIdEntity() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The second argument `$idReader` 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') diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/DataTransformer/CollectionToArrayTransformerTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/DataTransformer/CollectionToArrayTransformerTest.php index 113e07e295..e2129dc66d 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/DataTransformer/CollectionToArrayTransformerTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/DataTransformer/CollectionToArrayTransformerTest.php @@ -65,11 +65,9 @@ class CollectionToArrayTransformerTest extends TestCase $this->assertSame([], $this->transformer->transform(null)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testTransformExpectsArrayOrCollection() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $this->transformer->transform('Foo'); } diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php index e27afceeb4..0c487dfe94 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php @@ -118,19 +118,15 @@ class EntityTypeTest extends BaseTypeTest // be managed! } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\MissingOptionsException - */ public function testClassOptionIsRequired() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\MissingOptionsException'); $this->factory->createNamed('name', static::TESTED_TYPE); } - /** - * @expectedException \Symfony\Component\Form\Exception\RuntimeException - */ public function testInvalidClassOption() { + $this->expectException('Symfony\Component\Form\Exception\RuntimeException'); $this->factory->createNamed('name', static::TESTED_TYPE, null, [ 'class' => 'foo', ]); @@ -190,11 +186,9 @@ class EntityTypeTest extends BaseTypeTest $this->assertEquals([1 => new ChoiceView($entity1, '1', 'Foo'), 2 => new ChoiceView($entity2, '2', 'Bar')], $view->vars['choices']); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testConfigureQueryBuilderWithNonQueryBuilderAndNonClosure() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $field = $this->factory->createNamed('name', static::TESTED_TYPE, null, [ 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, @@ -202,11 +196,9 @@ class EntityTypeTest extends BaseTypeTest ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException - */ public function testConfigureQueryBuilderWithClosureReturningNonQueryBuilder() { + $this->expectException('Symfony\Component\Form\Exception\UnexpectedTypeException'); $field = $this->factory->createNamed('name', static::TESTED_TYPE, null, [ 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, diff --git a/src/Symfony/Bridge/Doctrine/Tests/Messenger/DoctrineTransactionMiddlewareTest.php b/src/Symfony/Bridge/Doctrine/Tests/Messenger/DoctrineTransactionMiddlewareTest.php index bb77786339..d6f15e2013 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Messenger/DoctrineTransactionMiddlewareTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Messenger/DoctrineTransactionMiddlewareTest.php @@ -53,12 +53,10 @@ class DoctrineTransactionMiddlewareTest extends MiddlewareTestCase $this->middleware->handle(new Envelope(new \stdClass()), $this->getStackMock()); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Thrown from next middleware. - */ public function testTransactionIsRolledBackOnException() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Thrown from next middleware.'); $this->connection->expects($this->once()) ->method('beginTransaction') ; diff --git a/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php b/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php index 06a40100e9..ba1023604e 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.php @@ -84,12 +84,10 @@ class EntityUserProviderTest extends TestCase $this->assertSame($user, $provider->loadUserByUsername('user1')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage 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. - */ public function testLoadUserByUsernameWithNonUserLoaderRepositoryAndWithoutProperty() { + $this->expectException('InvalidArgumentException'); + $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); @@ -168,11 +166,9 @@ class EntityUserProviderTest extends TestCase $provider->loadUserByUsername('name'); } - /** - * @expectedException \InvalidArgumentException - */ public function testLoadUserByUserNameShouldDeclineInvalidInterface() { + $this->expectException('InvalidArgumentException'); $repository = $this->getMockBuilder(EntityRepository::class)->disableOriginalConstructor()->getMock(); $provider = new EntityUserProvider( diff --git a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php index e5eaf0138e..15e3b5f796 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php @@ -278,11 +278,9 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase ->assertRaised(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testAllConfiguredFieldsAreCheckedOfBeingMappedByDoctrineWithIgnoreNullEnabled() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $constraint = new UniqueEntity([ 'message' => 'myMessage', 'fields' => ['name', 'name2'], @@ -589,12 +587,10 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase ->assertRaised(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage Object manager "foo" does not exist. - */ public function testDedicatedEntityManagerNullObject() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('Object manager "foo" does not exist.'); $constraint = new UniqueEntity([ 'message' => 'myMessage', 'fields' => ['name'], @@ -611,12 +607,10 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase $this->validator->validate($entity, $constraint); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage Unable to find the object manager associated with an entity of class "Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity" - */ public function testEntityManagerNullObject() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $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'], @@ -695,12 +689,10 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase ->assertRaised(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage 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". - */ public function testInvalidateRepositoryForInheritance() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $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'], diff --git a/src/Symfony/Bridge/Monolog/Tests/Handler/FingersCrossed/HttpCodeActivationStrategyTest.php b/src/Symfony/Bridge/Monolog/Tests/Handler/FingersCrossed/HttpCodeActivationStrategyTest.php index 0fce18d386..75bbe16c14 100644 --- a/src/Symfony/Bridge/Monolog/Tests/Handler/FingersCrossed/HttpCodeActivationStrategyTest.php +++ b/src/Symfony/Bridge/Monolog/Tests/Handler/FingersCrossed/HttpCodeActivationStrategyTest.php @@ -20,19 +20,15 @@ use Symfony\Component\HttpKernel\Exception\HttpException; class HttpCodeActivationStrategyTest extends TestCase { - /** - * @expectedException \LogicException - */ public function testExclusionsWithoutCode() { + $this->expectException('LogicException'); new HttpCodeActivationStrategy(new RequestStack(), [['urls' => []]], Logger::WARNING); } - /** - * @expectedException \LogicException - */ public function testExclusionsWithoutUrls() { + $this->expectException('LogicException'); new HttpCodeActivationStrategy(new RequestStack(), [['code' => 404]], Logger::WARNING); } diff --git a/src/Symfony/Bridge/Twig/Tests/AppVariableTest.php b/src/Symfony/Bridge/Twig/Tests/AppVariableTest.php index 7fde1bf95f..04b137740a 100644 --- a/src/Symfony/Bridge/Twig/Tests/AppVariableTest.php +++ b/src/Symfony/Bridge/Twig/Tests/AppVariableTest.php @@ -117,51 +117,39 @@ class AppVariableTest extends TestCase $this->assertNull($this->appVariable->getUser()); } - /** - * @expectedException \RuntimeException - */ public function testEnvironmentNotSet() { + $this->expectException('RuntimeException'); $this->appVariable->getEnvironment(); } - /** - * @expectedException \RuntimeException - */ public function testDebugNotSet() { + $this->expectException('RuntimeException'); $this->appVariable->getDebug(); } - /** - * @expectedException \RuntimeException - */ public function testGetTokenWithTokenStorageNotSet() { + $this->expectException('RuntimeException'); $this->appVariable->getToken(); } - /** - * @expectedException \RuntimeException - */ public function testGetUserWithTokenStorageNotSet() { + $this->expectException('RuntimeException'); $this->appVariable->getUser(); } - /** - * @expectedException \RuntimeException - */ public function testGetRequestWithRequestStackNotSet() { + $this->expectException('RuntimeException'); $this->appVariable->getRequest(); } - /** - * @expectedException \RuntimeException - */ public function testGetSessionWithRequestStackNotSet() { + $this->expectException('RuntimeException'); $this->appVariable->getSession(); } diff --git a/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php b/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php index 5417f05b7e..43d25301d0 100644 --- a/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php @@ -63,12 +63,10 @@ class DebugCommandTest extends TestCase $this->assertEquals($expected, json_decode($tester->getDisplay(true), true)); } - /** - * @expectedException \Symfony\Component\Console\Exception\InvalidArgumentException - * @expectedExceptionMessage Malformed namespaced template name "@foo" (expecting "@namespace/template_name"). - */ public function testMalformedTemplateName() { + $this->expectException('Symfony\Component\Console\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Malformed namespaced template name "@foo" (expecting "@namespace/template_name").'); $this->createCommandTester()->execute(['name' => '@foo']); } diff --git a/src/Symfony/Bridge/Twig/Tests/Command/LintCommandTest.php b/src/Symfony/Bridge/Twig/Tests/Command/LintCommandTest.php index fc1d248026..8a3904846c 100644 --- a/src/Symfony/Bridge/Twig/Tests/Command/LintCommandTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Command/LintCommandTest.php @@ -48,11 +48,9 @@ class LintCommandTest extends TestCase $this->assertRegExp('/ERROR in \S+ \(line /', trim($tester->getDisplay())); } - /** - * @expectedException \RuntimeException - */ public function testLintFileNotReadable() { + $this->expectException('RuntimeException'); $tester = $this->createCommandTester(); $filename = $this->createFile(''); unlink($filename); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php index d3d64f0538..bcee512a21 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php @@ -25,11 +25,9 @@ class HttpKernelExtensionTest extends TestCase { use ForwardCompatTestTrait; - /** - * @expectedException \Twig\Error\RuntimeError - */ public function testFragmentWithError() { + $this->expectException('Twig\Error\RuntimeError'); $renderer = $this->getFragmentHandler($this->throwException(new \Exception('foo'))); $this->renderTemplate($renderer); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.php index 1af65e4c19..cac643f45b 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.php @@ -12,6 +12,7 @@ namespace Symfony\Bridge\Twig\Tests\Extension; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Bridge\Twig\Extension\StopwatchExtension; use Twig\Environment; use Twig\Error\RuntimeError; @@ -19,11 +20,11 @@ use Twig\Loader\ArrayLoader; class StopwatchExtensionTest extends TestCase { - /** - * @expectedException \Twig\Error\SyntaxError - */ + use ForwardCompatTestTrait; + public function testFailIfStoppingWrongEvent() { + $this->expectException('Twig\Error\SyntaxError'); $this->testTiming('{% stopwatch "foo" %}{% endstopwatch "bar" %}', []); } diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.php index 1757acacdd..4f8de382ce 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.php @@ -12,6 +12,7 @@ namespace Symfony\Bridge\Twig\Tests\Extension; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Bridge\Twig\Extension\TranslationExtension; use Symfony\Component\Translation\Loader\ArrayLoader; use Symfony\Component\Translation\Translator; @@ -20,6 +21,8 @@ use Twig\Loader\ArrayLoader as TwigArrayLoader; class TranslationExtensionTest extends TestCase { + use ForwardCompatTestTrait; + public function testEscaping() { $output = $this->getTemplate('{% trans %}Percent: %value%%% (%msg%){% endtrans %}')->render(['value' => 12, 'msg' => 'approx.']); @@ -45,21 +48,17 @@ class TranslationExtensionTest extends TestCase $this->assertEquals($expected, $this->getTemplate($template)->render($variables)); } - /** - * @expectedException \Twig\Error\SyntaxError - * @expectedExceptionMessage Unexpected token. Twig was looking for the "with", "from", or "into" keyword in "index" at line 3. - */ public function testTransUnknownKeyword() { + $this->expectException('Twig\Error\SyntaxError'); + $this->expectExceptionMessage('Unexpected token. Twig was looking for the "with", "from", or "into" keyword in "index" at line 3.'); $output = $this->getTemplate("{% trans \n\nfoo %}{% endtrans %}")->render(); } - /** - * @expectedException \Twig\Error\SyntaxError - * @expectedExceptionMessage A message inside a trans tag must be a simple text in "index" at line 2. - */ public function testTransComplexBody() { + $this->expectException('Twig\Error\SyntaxError'); + $this->expectExceptionMessage('A message inside a trans tag must be a simple text in "index" at line 2.'); $output = $this->getTemplate("{% trans %}\n{{ 1 + 2 }}{% endtrans %}")->render(); } diff --git a/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php b/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php index 608f7241f4..bf3703fd54 100644 --- a/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php @@ -12,6 +12,7 @@ namespace Symfony\Bridge\Twig\Tests\Translation; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Bridge\Twig\Extension\TranslationExtension; use Symfony\Bridge\Twig\Translation\TwigExtractor; use Symfony\Component\Translation\MessageCatalogue; @@ -22,6 +23,8 @@ use Twig\Loader\ArrayLoader; class TwigExtractorTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getExtractData */ @@ -72,11 +75,11 @@ class TwigExtractorTest extends TestCase } /** - * @expectedException \Twig\Error\Error * @dataProvider resourcesWithSyntaxErrorsProvider */ public function testExtractSyntaxError($resources) { + $this->expectException('Twig\Error\Error'); $twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock()); $twig->addExtension(new TranslationExtension($this->getMockBuilder(TranslatorInterface::class)->getMock())); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php index 0d5073d1af..1a69c06115 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php @@ -99,11 +99,9 @@ class TranslationDebugCommandTest extends TestCase $this->assertRegExp('/unused/', $tester->getDisplay()); } - /** - * @expectedException \InvalidArgumentException - */ public function testDebugInvalidDirectory() { + $this->expectException('InvalidArgumentException'); $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock(); $kernel->expects($this->once()) ->method('getBundle') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/YamlLintCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/YamlLintCommandTest.php index 6c3c0aa74a..9ace567307 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/YamlLintCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/YamlLintCommandTest.php @@ -61,11 +61,9 @@ bar'; $this->assertContains('Unable to parse at line 3 (near "bar").', trim($tester->getDisplay())); } - /** - * @expectedException \RuntimeException - */ public function testLintFileNotReadable() { + $this->expectException('RuntimeException'); $tester = $this->createCommandTester(); $filename = $this->createFile(''); unlink($filename); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php index fca2b25fa7..77769e1e98 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php @@ -80,12 +80,10 @@ class AbstractControllerTest extends TestCase $this->assertSame('bar', $controller->getParameter('foo')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage TestAbstractController::getParameter()" method is missing a parameter bag - */ public function testMissingParameterBag() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $this->expectExceptionMessage('TestAbstractController::getParameter()" method is missing a parameter bag'); $container = new Container(); $controller = $this->createController(); @@ -148,12 +146,11 @@ class AbstractControllerTest extends TestCase $this->assertNull($controller->getUser()); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage The SecurityBundle is not registered in your application. - */ public function testGetUserWithEmptyContainer() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('The SecurityBundle is not registered in your application.'); + $controller = $this->createController(); $controller->setContainer(new Container()); @@ -335,11 +332,10 @@ class AbstractControllerTest extends TestCase $this->assertContains('test.php', $response->headers->get('content-disposition')); } - /** - * @expectedException \Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException - */ public function testFileWhichDoesNotExist() { + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); + $controller = $this->createController(); /* @var BinaryFileResponse $response */ @@ -360,11 +356,10 @@ class AbstractControllerTest extends TestCase $this->assertTrue($controller->isGranted('foo')); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException - */ public function testdenyAccessUnlessGranted() { + $this->expectException('Symfony\Component\Security\Core\Exception\AccessDeniedException'); + $authorizationChecker = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface')->getMock(); $authorizationChecker->expects($this->once())->method('isGranted')->willReturn(false); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php index 2cdb2e698a..b35c6d6cbd 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php @@ -66,12 +66,11 @@ class ControllerResolverTest extends ContainerControllerResolverTest $this->assertSame($container, $controller->getContainer()); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage "Symfony\Bundle\FrameworkBundle\Tests\Controller\TestAbstractController" has no container set, did you forget to define it as a service subscriber? - */ public function testAbstractControllerGetsContainerWhenNotSet() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('"Symfony\\Bundle\\FrameworkBundle\\Tests\\Controller\\TestAbstractController" has no container set, did you forget to define it as a service subscriber?'); + class_exists(AbstractControllerTest::class); $controller = new TestAbstractController(false); @@ -88,12 +87,11 @@ class ControllerResolverTest extends ContainerControllerResolverTest $this->assertSame($container, $controller->setContainer($container)); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage "Symfony\Bundle\FrameworkBundle\Tests\Controller\DummyController" has no container set, did you forget to define it as a service subscriber? - */ public function testAbstractControllerServiceWithFqcnIdGetsContainerWhenNotSet() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('"Symfony\\Bundle\\FrameworkBundle\\Tests\\Controller\\DummyController" has no container set, did you forget to define it as a service subscriber?'); + class_exists(AbstractControllerTest::class); $controller = new DummyController(); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php index f35b9bc5d6..bb220d14cc 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php @@ -11,6 +11,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Controller; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Bundle\FrameworkBundle\Controller\TemplateController; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; @@ -19,6 +20,8 @@ use Symfony\Bundle\FrameworkBundle\Tests\TestCase; */ class TemplateControllerTest extends TestCase { + use ForwardCompatTestTrait; + public function testTwig() { $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); @@ -30,12 +33,10 @@ class TemplateControllerTest extends TestCase $this->assertEquals('bar', $controller('mytemplate')->getContent()); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage You can not use the TemplateController if the Twig Bundle is not available. - */ public function testNoTwig() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('You can not use the TemplateController if the Twig Bundle is not available.'); $controller = new TemplateController(); $controller->templateAction('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 b693165f8b..bb4c5e00b4 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/ProfilerPassTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/ProfilerPassTest.php @@ -12,11 +12,14 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ProfilerPass; use Symfony\Component\DependencyInjection\ContainerBuilder; class ProfilerPassTest extends TestCase { + use ForwardCompatTestTrait; + /** * Tests that collectors that specify a template but no "id" will throw * an exception (both are needed if the template is specified). @@ -24,11 +27,10 @@ class ProfilerPassTest extends TestCase * Thus, a fully-valid tag looks something like this: * * - * - * @expectedException \InvalidArgumentException */ public function testTemplateNoIdThrowsException() { + $this->expectException('InvalidArgumentException'); $builder = new ContainerBuilder(); $builder->register('profiler', 'ProfilerClass'); $builder->register('my_collector_service') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php index c20660820b..e1595fabc3 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php @@ -55,12 +55,10 @@ class WorkflowGuardListenerPassTest extends TestCase $this->assertFalse($this->container->hasParameter('workflow.has_guard_listeners')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException - * @expectedExceptionMessage The "security.token_storage" service is needed to be able to use the workflow guard listener. - */ public function testExceptionIfTheTokenStorageServiceIsNotPresent() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException'); + $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); @@ -69,12 +67,10 @@ class WorkflowGuardListenerPassTest extends TestCase $this->compilerPass->process($this->container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException - * @expectedExceptionMessage The "security.authorization_checker" service is needed to be able to use the workflow guard listener. - */ public function testExceptionIfTheAuthorizationCheckerServiceIsNotPresent() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException'); + $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); @@ -83,12 +79,10 @@ class WorkflowGuardListenerPassTest extends TestCase $this->compilerPass->process($this->container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException - * @expectedExceptionMessage The "security.authentication.trust_resolver" service is needed to be able to use the workflow guard listener. - */ public function testExceptionIfTheAuthenticationTrustResolverServiceIsNotPresent() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException'); + $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); @@ -97,12 +91,10 @@ class WorkflowGuardListenerPassTest extends TestCase $this->compilerPass->process($this->container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException - * @expectedExceptionMessage The "security.role_hierarchy" service is needed to be able to use the workflow guard listener. - */ public function testExceptionIfTheRoleHierarchyServiceIsNotPresent() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException'); + $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); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php index fb61e11bce..8bb85507ee 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php @@ -50,10 +50,10 @@ class ConfigurationTest extends TestCase /** * @dataProvider getTestInvalidSessionName - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException */ public function testInvalidSessionName($sessionName) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $processor = new Processor(); $processor->processConfiguration( new Configuration(true), diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php index 220bff1764..05a69dd8f8 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php @@ -13,6 +13,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection; use Doctrine\Common\Annotations\Annotation; use Psr\Log\LoggerAwareInterface; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddAnnotationsCachedReaderPass; use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; @@ -57,6 +58,8 @@ use Symfony\Component\Workflow; abstract class FrameworkExtensionTest extends TestCase { + use ForwardCompatTestTrait; + private static $containerCache = []; abstract protected function loadFromFile(ContainerBuilder $container, $file); @@ -118,12 +121,10 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertSame(ArrayAdapter::class, $cache->getClass(), 'ArrayAdapter should be used in debug mode'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage CSRF protection needs sessions to be enabled. - */ public function testCsrfProtectionNeedsSessionToBeEnabled() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('CSRF protection needs sessions to be enabled.'); $this->createContainerFromFile('csrf_needs_session'); } @@ -275,30 +276,24 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertGreaterThan(0, \count($registryDefinition->getMethodCalls())); } - /** - * @expectedException \Symfony\Component\Workflow\Exception\InvalidDefinitionException - * @expectedExceptionMessage A transition from a place/state must have an unique name. Multiple transitions named "go" from place/state "first" where found on StateMachine "my_workflow". - */ public function testWorkflowAreValidated() { + $this->expectException('Symfony\Component\Workflow\Exception\InvalidDefinitionException'); + $this->expectExceptionMessage('A transition from a place/state must have an unique name. Multiple transitions named "go" from place/state "first" where found on StateMachine "my_workflow".'); $this->createContainerFromFile('workflow_not_valid'); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage "supports" and "support_strategy" cannot be used together. - */ public function testWorkflowCannotHaveBothSupportsAndSupportStrategy() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('"supports" and "support_strategy" cannot be used together.'); $this->createContainerFromFile('workflow_with_support_and_support_strategy'); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage "supports" or "support_strategy" should be configured. - */ public function testWorkflowShouldHaveOneOfSupportsAndSupportStrategy() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('"supports" or "support_strategy" should be configured.'); $this->createContainerFromFile('workflow_without_support_and_support_strategy'); } @@ -457,11 +452,9 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertEquals('xml', $arguments[2]['resource_type'], '->registerRouterConfiguration() sets routing resource type'); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - */ public function testRouterRequiresResourceOption() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $container = $this->createContainer(); $loader = new FrameworkExtension(); $loader->load([['router' => true]], $container); @@ -503,11 +496,9 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertEquals($expected, array_keys($container->getDefinition('session_listener')->getArgument(0)->getValues())); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - */ public function testNullSessionHandlerWithSavePath() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $this->createContainerFromFile('session_savepath'); } @@ -681,12 +672,10 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertSame('messenger.bus.commands', (string) $container->getAlias('messenger.default_bus')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid middleware at path "framework.messenger": a map with a single factory id as key and its arguments as value was expected, {"foo":["qux"],"bar":["baz"]} given. - */ public function testMessengerMiddlewareFactoryErroneousFormat() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Invalid middleware at path "framework.messenger": a map with a single factory id as key and its arguments as value was expected, {"foo":["qux"],"bar":["baz"]} given.'); $this->createContainerFromFile('messenger_middleware_factory_erroneous_format'); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php index 94c5cab184..1d90484df0 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php @@ -11,23 +11,24 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; class PhpFrameworkExtensionTest extends FrameworkExtensionTest { + use ForwardCompatTestTrait; + protected function loadFromFile(ContainerBuilder $container, $file) { $loader = new PhpFileLoader($container, new FileLocator(__DIR__.'/Fixtures/php')); $loader->load($file.'.php'); } - /** - * @expectedException \LogicException - */ public function testAssetsCannotHavePathAndUrl() { + $this->expectException('LogicException'); $this->createContainerFromClosure(function ($container) { $container->loadFromExtension('framework', [ 'assets' => [ @@ -38,11 +39,9 @@ class PhpFrameworkExtensionTest extends FrameworkExtensionTest }); } - /** - * @expectedException \LogicException - */ public function testAssetPackageCannotHavePathAndUrl() { + $this->expectException('LogicException'); $this->createContainerFromClosure(function ($container) { $container->loadFromExtension('framework', [ 'assets' => [ @@ -57,12 +56,10 @@ class PhpFrameworkExtensionTest extends FrameworkExtensionTest }); } - /** - * @expectedException \Symfony\Component\Workflow\Exception\InvalidDefinitionException - * @expectedExceptionMessage A transition from a place/state must have an unique name. Multiple transitions named "a_to_b" from place/state "a" where found on StateMachine "article". - */ public function testWorkflowValidationStateMachine() { + $this->expectException('Symfony\Component\Workflow\Exception\InvalidDefinitionException'); + $this->expectExceptionMessage('A transition from a place/state must have an unique name. Multiple transitions named "a_to_b" from place/state "a" where found on StateMachine "article".'); $this->createContainerFromClosure(function ($container) { $container->loadFromExtension('framework', [ 'workflows' => [ diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolClearCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolClearCommandTest.php index e69275bdad..d2df3fec45 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolClearCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolClearCommandTest.php @@ -68,12 +68,10 @@ class CachePoolClearCommandTest extends AbstractWebTestCase $this->assertContains('[OK] Cache was successfully cleared.', $tester->getDisplay()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage You have requested a non-existent service "unknown_pool" - */ public function testClearUnexistingPool() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $this->expectExceptionMessage('You have requested a non-existent service "unknown_pool"'); $this->createCommandTester() ->execute(['pools' => ['unknown_pool']], ['decorated' => false]); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolsTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolsTest.php index 81b5d66a41..42ae5eaabe 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolsTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolsTest.php @@ -11,6 +11,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Functional; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Cache\Adapter\AdapterInterface; use Symfony\Component\Cache\Adapter\RedisAdapter; use Symfony\Component\Cache\Adapter\TagAwareAdapter; @@ -18,6 +19,8 @@ use Symfony\Component\Cache\Exception\InvalidArgumentException; class CachePoolsTest extends AbstractWebTestCase { + use ForwardCompatTestTrait; + public function testCachePools() { $this->doTestCachePools([], AdapterInterface::class); @@ -35,7 +38,7 @@ class CachePoolsTest extends AbstractWebTestCase throw $e; } $this->markTestSkipped($e->getMessage()); - } catch (\PHPUnit_Framework_Error_Warning $e) { + } catch (\PHPUnit\Framework\Error\Warning $e) { if (0 !== strpos($e->getMessage(), 'unable to connect to')) { throw $e; } @@ -60,7 +63,7 @@ class CachePoolsTest extends AbstractWebTestCase throw $e; } $this->markTestSkipped($e->getMessage()); - } catch (\PHPUnit_Framework_Error_Warning $e) { + } catch (\PHPUnit\Framework\Error\Warning $e) { if (0 !== strpos($e->getMessage(), 'unable to connect to')) { throw $e; } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/RouterDebugCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/RouterDebugCommandTest.php index c7c7ac9ace..629e41b7ce 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/RouterDebugCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/RouterDebugCommandTest.php @@ -61,12 +61,10 @@ class RouterDebugCommandTest extends AbstractWebTestCase $this->assertContains('/test', $tester->getDisplay()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The route "gerard" does not exist. - */ public function testSearchWithThrow() { + $this->expectException('InvalidArgumentException'); + $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 3b8efc2bfa..23c2f39d07 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RouterTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RouterTest.php @@ -13,6 +13,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Routing; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Bundle\FrameworkBundle\Routing\Router; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\Config\ContainerParametersResource; @@ -21,12 +22,12 @@ use Symfony\Component\Routing\RouteCollection; class RouterTest extends TestCase { - /** - * @expectedException \LogicException - * @expectedExceptionMessage You should either pass a "Symfony\Component\DependencyInjection\ContainerInterface" instance or provide the $parameters argument of the "Symfony\Bundle\FrameworkBundle\Routing\Router::__construct" method - */ + use ForwardCompatTestTrait; + public function testConstructThrowsOnNonSymfonyNorPsr11Container() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('You should either pass a "Symfony\Component\DependencyInjection\ContainerInterface" instance or provide the $parameters argument of the "Symfony\Bundle\FrameworkBundle\Routing\Router::__construct" method'); new Router($this->createMock(ContainerInterface::class), 'foo'); } @@ -291,12 +292,10 @@ class RouterTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Using "%env(FOO)%" is not allowed in routing configuration. - */ public function testEnvPlaceholders() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Using "%env(FOO)%" is not allowed in routing configuration.'); $routes = new RouteCollection(); $routes->add('foo', new Route('/%env(FOO)%')); @@ -305,12 +304,10 @@ class RouterTest extends TestCase $router->getRouteCollection(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Using "%env(FOO)%" is not allowed in routing configuration. - */ public function testEnvPlaceholdersWithSfContainer() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Using "%env(FOO)%" is not allowed in routing configuration.'); $routes = new RouteCollection(); $routes->add('foo', new Route('/%env(FOO)%')); @@ -361,12 +358,10 @@ class RouterTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException - * @expectedExceptionMessage You have requested a non-existent parameter "nope". - */ public function testExceptionOnNonExistentParameterWithSfContainer() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException'); + $this->expectExceptionMessage('You have requested a non-existent parameter "nope".'); $routes = new RouteCollection(); $routes->add('foo', new Route('/%nope%')); @@ -377,12 +372,10 @@ class RouterTest extends TestCase $router->getRouteCollection()->get('foo'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The container parameter "object", used in the route configuration value "/%object%", must be a string or numeric, but it is of type object. - */ public function testExceptionOnNonStringParameter() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The container parameter "object", used in the route configuration value "/%object%", must be a string or numeric, but it is of type object.'); $routes = new RouteCollection(); $routes->add('foo', new Route('/%object%')); @@ -394,12 +387,10 @@ class RouterTest extends TestCase $router->getRouteCollection()->get('foo'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The container parameter "object", used in the route configuration value "/%object%", must be a string or numeric, but it is of type object. - */ public function testExceptionOnNonStringParameterWithSfContainer() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The container parameter "object", used in the route configuration value "/%object%", must be a string or numeric, but it is of type object.'); $routes = new RouteCollection(); $routes->add('foo', new Route('/%object%')); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php index 6f478ef0d3..331b4f4a90 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php @@ -99,12 +99,10 @@ class TranslatorTest extends TestCase $this->assertEquals('foobarbax (sr@latin)', $translator->trans('foobarbax')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid "invalid locale" locale. - */ public function testTransWithCachingWithInvalidLocale() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Invalid "invalid locale" locale.'); $loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock(); $translator = $this->getTranslator($loader, ['cache_dir' => $this->tmpDir], 'loader', '\Symfony\Bundle\FrameworkBundle\Tests\Translation\TranslatorWithInvalidLocale'); @@ -134,12 +132,10 @@ class TranslatorTest extends TestCase $this->assertSame('en', $translator->getLocale()); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidArgumentException - * @expectedExceptionMessage The Translator does not support the following options: 'foo' - */ public function testInvalidOptions() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The Translator does not support the following options: \'foo\''); $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); (new Translator($container, new MessageFormatter(), 'en', [], ['foo' => 'bar'])); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSecurityVotersPassTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSecurityVotersPassTest.php index c3cc3fd09a..3b95ff23ec 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSecurityVotersPassTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSecurityVotersPassTest.php @@ -25,12 +25,10 @@ class AddSecurityVotersPassTest extends TestCase { use ForwardCompatTestTrait; - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException - * @expectedExceptionMessage No security voters found. You need to tag at least one with "security.voter". - */ public function testNoVoters() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException'); + $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) diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php index 415d3f946e..e97902d706 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php @@ -12,6 +12,7 @@ namespace Symfony\Bundle\SecurityBundle\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension; use Symfony\Bundle\SecurityBundle\SecurityBundle; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; @@ -22,6 +23,8 @@ use Symfony\Component\Security\Core\Encoder\SodiumPasswordEncoder; abstract class CompleteConfigurationTest extends TestCase { + use ForwardCompatTestTrait; + abstract protected function getLoader(ContainerBuilder $container); abstract protected function getFileExtension(); @@ -418,12 +421,10 @@ abstract class CompleteConfigurationTest extends TestCase $this->assertSame('app.access_decision_manager', (string) $container->getAlias('security.access.decision_manager'), 'The custom access decision manager service is aliased'); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage Invalid configuration for path "security.access_decision_manager": "strategy" and "service" cannot be used together. - */ public function testAccessDecisionManagerServiceAndStrategyCannotBeUsedAtTheSameTime() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('Invalid configuration for path "security.access_decision_manager": "strategy" and "service" cannot be used together.'); $this->getContainer('access_decision_manager_service_and_strategy'); } @@ -438,21 +439,17 @@ abstract class CompleteConfigurationTest extends TestCase $this->assertFalse($accessDecisionManagerDefinition->getArgument(3)); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage Invalid firewall "main": user provider "undefined" not found. - */ public function testFirewallUndefinedUserProvider() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('Invalid firewall "main": user provider "undefined" not found.'); $this->getContainer('firewall_undefined_provider'); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage Invalid firewall "main": user provider "undefined" not found. - */ public function testFirewallListenerUndefinedProvider() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('Invalid firewall "main": user provider "undefined" not found.'); $this->getContainer('listener_undefined_provider'); } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/MainConfigurationTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/MainConfigurationTest.php index 88565a47cd..5f9307fb67 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/MainConfigurationTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/MainConfigurationTest.php @@ -12,11 +12,14 @@ namespace Symfony\Bundle\SecurityBundle\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Bundle\SecurityBundle\DependencyInjection\MainConfiguration; use Symfony\Component\Config\Definition\Processor; class MainConfigurationTest extends TestCase { + use ForwardCompatTestTrait; + /** * The minimal, required config needed to not have any required validation * issues. @@ -32,11 +35,9 @@ class MainConfigurationTest extends TestCase ], ]; - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - */ public function testNoConfigForProvider() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $config = [ 'providers' => [ 'stub' => [], @@ -48,11 +49,9 @@ class MainConfigurationTest extends TestCase $processor->processConfiguration($configuration, [$config]); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - */ public function testManyConfigForProvider() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $config = [ 'providers' => [ 'stub' => [ diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/GuardAuthenticationFactoryTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/GuardAuthenticationFactoryTest.php index 81db40412a..b6fa11875b 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/GuardAuthenticationFactoryTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Security/Factory/GuardAuthenticationFactoryTest.php @@ -12,6 +12,7 @@ namespace Symfony\Bundle\SecurityBundle\Tests\DependencyInjection\Security\Factory; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\GuardAuthenticationFactory; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; @@ -20,6 +21,8 @@ use Symfony\Component\DependencyInjection\Reference; class GuardAuthenticationFactoryTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getValidConfigurationTests */ @@ -37,11 +40,11 @@ class GuardAuthenticationFactoryTest extends TestCase } /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException * @dataProvider getInvalidConfigurationTests */ public function testAddInvalidConfiguration(array $inputConfig) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $factory = new GuardAuthenticationFactory(); $nodeDefinition = new ArrayNodeDefinition('guard'); $factory->addConfiguration($nodeDefinition); @@ -130,11 +133,9 @@ class GuardAuthenticationFactoryTest extends TestCase $this->assertEquals('some_default_entry_point', $entryPointId); } - /** - * @expectedException \LogicException - */ public function testCannotOverrideDefaultEntryPoint() { + $this->expectException('LogicException'); // any existing default entry point is used $config = [ 'authenticators' => ['authenticator123'], @@ -143,11 +144,9 @@ class GuardAuthenticationFactoryTest extends TestCase $this->executeCreate($config, 'some_default_entry_point'); } - /** - * @expectedException \LogicException - */ public function testMultipleAuthenticatorsRequiresEntryPoint() { + $this->expectException('LogicException'); // any existing default entry point is used $config = [ 'authenticators' => ['authenticator123', 'authenticatorABC'], diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php index 5d55295b5e..d1a7b3f586 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php @@ -12,6 +12,7 @@ namespace Symfony\Bundle\SecurityBundle\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension; use Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension; use Symfony\Bundle\SecurityBundle\SecurityBundle; @@ -24,12 +25,12 @@ use Symfony\Component\Security\Core\User\UserProviderInterface; class SecurityExtensionTest extends TestCase { - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The check_path "/some_area/login_check" for login method "form_login" is not matched by the firewall pattern "/secured_area/.*". - */ + use ForwardCompatTestTrait; + public function testInvalidCheckPath() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $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', [ @@ -50,12 +51,10 @@ class SecurityExtensionTest extends TestCase $container->compile(); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage No authentication listener registered for firewall "some_firewall" - */ public function testFirewallWithoutAuthenticationListener() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('No authentication listener registered for firewall "some_firewall"'); $container = $this->getRawContainer(); $container->loadFromExtension('security', [ @@ -73,12 +72,10 @@ class SecurityExtensionTest extends TestCase $container->compile(); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage Unable to create definition for "security.user.provider.concrete.my_foo" user provider - */ public function testFirewallWithInvalidUserProvider() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('Unable to create definition for "security.user.provider.concrete.my_foo" user provider'); $container = $this->getRawContainer(); $extension = $container->getExtension('security'); @@ -194,12 +191,10 @@ class SecurityExtensionTest extends TestCase $this->addToAssertionCount(1); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage Not configuring explicitly the provider for the "http_basic" listener on "ambiguous" firewall is ambiguous as there is more than one registered provider. - */ public function testMissingProviderForListener() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('Not configuring explicitly the provider for the "http_basic" listener on "ambiguous" firewall is ambiguous as there is more than one registered provider.'); $container = $this->getRawContainer(); $container->loadFromExtension('security', [ 'providers' => [ diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/MissingUserProviderTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/MissingUserProviderTest.php index d645f97f5b..6231bde641 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/MissingUserProviderTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/MissingUserProviderTest.php @@ -13,12 +13,10 @@ namespace Symfony\Bundle\SecurityBundle\Tests\Functional; class MissingUserProviderTest extends AbstractWebTestCase { - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage "default" firewall requires a user provider but none was defined. - */ public function testUserProviderIsNeeded() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('"default" firewall requires a user provider but none was defined.'); $client = $this->createClient(['test_case' => 'MissingUserProvider', 'root_config' => 'config.yml']); $client->request('GET', '/', [], [], [ diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/UserPasswordEncoderCommandTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/UserPasswordEncoderCommandTest.php index 6a2f69cf58..a691e70a20 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/UserPasswordEncoderCommandTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/UserPasswordEncoderCommandTest.php @@ -207,12 +207,10 @@ EOTXT $this->assertContains('Encoder used Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder', $this->passwordEncoderCommandTester->getDisplay()); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage There are no configured encoders for the "security" extension. - */ public function testThrowsExceptionOnNoConfiguredEncoders() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('There are no configured encoders for the "security" extension.'); $application = new ConsoleApplication(); $application->add(new UserPasswordEncoderCommand($this->getMockBuilder(EncoderFactoryInterface::class)->getMock(), [])); diff --git a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Compiler/TwigLoaderPassTest.php b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Compiler/TwigLoaderPassTest.php index a65aa03c57..46911e37c7 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Compiler/TwigLoaderPassTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Compiler/TwigLoaderPassTest.php @@ -90,11 +90,9 @@ class TwigLoaderPassTest extends TestCase $this->assertEquals('test_loader_1', (string) $calls[1][1][0]); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException - */ public function testMapperPassWithZeroTaggedLoaders() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException'); $this->pass->process($this->builder); } } diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php index 4c68f479b2..b492a02532 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php @@ -56,11 +56,9 @@ class TemplateManagerTest extends TestCase $this->templateManager = new TemplateManager($profiler, $twigEnvironment, $templates); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException - */ public function testGetNameOfInvalidTemplate() { + $this->expectException('Symfony\Component\HttpKernel\Exception\NotFoundHttpException'); $this->templateManager->getName(new Profile('token'), 'notexistingpanel'); } diff --git a/src/Symfony/Component/Asset/Tests/PackagesTest.php b/src/Symfony/Component/Asset/Tests/PackagesTest.php index b751986d48..0ab1505a8a 100644 --- a/src/Symfony/Component/Asset/Tests/PackagesTest.php +++ b/src/Symfony/Component/Asset/Tests/PackagesTest.php @@ -12,12 +12,15 @@ namespace Symfony\Component\Asset\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Asset\Package; use Symfony\Component\Asset\Packages; use Symfony\Component\Asset\VersionStrategy\StaticVersionStrategy; class PackagesTest extends TestCase { + use ForwardCompatTestTrait; + public function testGetterSetters() { $packages = new Packages(); @@ -55,20 +58,16 @@ class PackagesTest extends TestCase $this->assertEquals('/foo?a', $packages->getUrl('/foo', 'a')); } - /** - * @expectedException \Symfony\Component\Asset\Exception\LogicException - */ public function testNoDefaultPackage() { + $this->expectException('Symfony\Component\Asset\Exception\LogicException'); $packages = new Packages(); $packages->getPackage(); } - /** - * @expectedException \Symfony\Component\Asset\Exception\InvalidArgumentException - */ public function testUndefinedPackage() { + $this->expectException('Symfony\Component\Asset\Exception\InvalidArgumentException'); $packages = new Packages(); $packages->getPackage('a'); } diff --git a/src/Symfony/Component/Asset/Tests/UrlPackageTest.php b/src/Symfony/Component/Asset/Tests/UrlPackageTest.php index 3bb06633d3..f213d6c490 100644 --- a/src/Symfony/Component/Asset/Tests/UrlPackageTest.php +++ b/src/Symfony/Component/Asset/Tests/UrlPackageTest.php @@ -12,12 +12,15 @@ namespace Symfony\Component\Asset\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Asset\UrlPackage; use Symfony\Component\Asset\VersionStrategy\EmptyVersionStrategy; use Symfony\Component\Asset\VersionStrategy\StaticVersionStrategy; class UrlPackageTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getConfigs */ @@ -95,21 +98,18 @@ class UrlPackageTest extends TestCase $this->assertEquals('https://cdn.com/bar/main.css', $package->getUrl('main.css')); } - /** - * @expectedException \Symfony\Component\Asset\Exception\LogicException - */ public function testNoBaseUrls() { + $this->expectException('Symfony\Component\Asset\Exception\LogicException'); new UrlPackage([], new EmptyVersionStrategy()); } /** * @dataProvider getWrongBaseUrlConfig - * - * @expectedException \Symfony\Component\Asset\Exception\InvalidArgumentException */ public function testWrongBaseUrl($baseUrls) { + $this->expectException('Symfony\Component\Asset\Exception\InvalidArgumentException'); new UrlPackage($baseUrls, new EmptyVersionStrategy()); } diff --git a/src/Symfony/Component/Asset/Tests/VersionStrategy/JsonManifestVersionStrategyTest.php b/src/Symfony/Component/Asset/Tests/VersionStrategy/JsonManifestVersionStrategyTest.php index 9da2b4ada2..83f6885a2c 100644 --- a/src/Symfony/Component/Asset/Tests/VersionStrategy/JsonManifestVersionStrategyTest.php +++ b/src/Symfony/Component/Asset/Tests/VersionStrategy/JsonManifestVersionStrategyTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Asset\Tests\VersionStrategy; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Asset\VersionStrategy\JsonManifestVersionStrategy; class JsonManifestVersionStrategyTest extends TestCase { + use ForwardCompatTestTrait; + public function testGetVersion() { $strategy = $this->createStrategy('manifest-valid.json'); @@ -37,21 +40,17 @@ class JsonManifestVersionStrategyTest extends TestCase $this->assertEquals('css/other.css', $strategy->getVersion('css/other.css')); } - /** - * @expectedException \RuntimeException - */ public function testMissingManifestFileThrowsException() { + $this->expectException('RuntimeException'); $strategy = $this->createStrategy('non-existent-file.json'); $strategy->getVersion('main.js'); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Error parsing JSON - */ public function testManifestFileWithBadJSONThrowsException() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Error parsing JSON'); $strategy = $this->createStrategy('manifest-invalid.json'); $strategy->getVersion('main.js'); } diff --git a/src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php b/src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php index fdab3b4c0d..294343c9a4 100644 --- a/src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php +++ b/src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php @@ -92,12 +92,11 @@ class AbstractBrowserTest extends TestCase $this->assertEquals('http://example.com/', $client->getRequest()->getUri(), '->getCrawler() returns the Request of the last request'); } - /** - * @expectedException \Symfony\Component\BrowserKit\Exception\BadMethodCallException - * @expectedExceptionMessage The "request()" method must be called before "Symfony\Component\BrowserKit\AbstractBrowser::getRequest()". - */ public function testGetRequestNull() { + $this->expectException('Symfony\Component\BrowserKit\Exception\BadMethodCallException'); + $this->expectExceptionMessage('The "request()" method must be called before "Symfony\\Component\\BrowserKit\\AbstractBrowser::getRequest()".'); + $client = $this->getBrowser(); $this->assertNull($client->getRequest()); } @@ -130,22 +129,20 @@ class AbstractBrowserTest extends TestCase $this->assertInstanceOf('Symfony\Component\BrowserKit\Response', $client->getResponse(), '->getCrawler() returns the Response of the last request'); } - /** - * @expectedException \Symfony\Component\BrowserKit\Exception\BadMethodCallException - * @expectedExceptionMessage The "request()" method must be called before "Symfony\Component\BrowserKit\AbstractBrowser::getResponse()". - */ public function testGetResponseNull() { + $this->expectException('Symfony\Component\BrowserKit\Exception\BadMethodCallException'); + $this->expectExceptionMessage('The "request()" method must be called before "Symfony\\Component\\BrowserKit\\AbstractBrowser::getResponse()".'); + $client = $this->getBrowser(); $this->assertNull($client->getResponse()); } - /** - * @expectedException \Symfony\Component\BrowserKit\Exception\BadMethodCallException - * @expectedExceptionMessage The "request()" method must be called before "Symfony\Component\BrowserKit\AbstractBrowser::getInternalResponse()". - */ public function testGetInternalResponseNull() { + $this->expectException('Symfony\Component\BrowserKit\Exception\BadMethodCallException'); + $this->expectExceptionMessage('The "request()" method must be called before "Symfony\\Component\\BrowserKit\\AbstractBrowser::getInternalResponse()".'); + $client = $this->getBrowser(); $this->assertNull($client->getInternalResponse()); } @@ -168,12 +165,11 @@ class AbstractBrowserTest extends TestCase $this->assertSame($crawler, $client->getCrawler(), '->getCrawler() returns the Crawler of the last request'); } - /** - * @expectedException \Symfony\Component\BrowserKit\Exception\BadMethodCallException - * @expectedExceptionMessage The "request()" method must be called before "Symfony\Component\BrowserKit\AbstractBrowser::getCrawler()". - */ public function testGetCrawlerNull() { + $this->expectException('Symfony\Component\BrowserKit\Exception\BadMethodCallException'); + $this->expectExceptionMessage('The "request()" method must be called before "Symfony\\Component\\BrowserKit\\AbstractBrowser::getCrawler()".'); + $client = $this->getBrowser(); $this->assertNull($client->getCrawler()); } @@ -873,12 +869,11 @@ class AbstractBrowserTest extends TestCase $this->assertInstanceOf('Symfony\Component\BrowserKit\Request', $client->getInternalRequest()); } - /** - * @expectedException \Symfony\Component\BrowserKit\Exception\BadMethodCallException - * @expectedExceptionMessage The "request()" method must be called before "Symfony\Component\BrowserKit\AbstractBrowser::getInternalRequest()". - */ public function testInternalRequestNull() { + $this->expectException('Symfony\Component\BrowserKit\Exception\BadMethodCallException'); + $this->expectExceptionMessage('The "request()" method must be called before "Symfony\\Component\\BrowserKit\\AbstractBrowser::getInternalRequest()".'); + $client = $this->getBrowser(); $this->assertNull($client->getInternalRequest()); } diff --git a/src/Symfony/Component/BrowserKit/Tests/CookieTest.php b/src/Symfony/Component/BrowserKit/Tests/CookieTest.php index 3423aec46e..9a669048fc 100644 --- a/src/Symfony/Component/BrowserKit/Tests/CookieTest.php +++ b/src/Symfony/Component/BrowserKit/Tests/CookieTest.php @@ -200,12 +200,10 @@ class CookieTest extends TestCase $this->assertFalse($cookie->isExpired()); } - /** - * @expectedException \UnexpectedValueException - * @expectedExceptionMessage The cookie expiration time "string" is not valid. - */ public function testConstructException() { + $this->expectException('UnexpectedValueException'); + $this->expectExceptionMessage('The cookie expiration time "string" is not valid.'); $cookie = new Cookie('foo', 'bar', 'string'); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php index 46bbef4c31..f502b45914 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Cache\Tests\Adapter; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Cache\Adapter\AdapterInterface; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\Adapter\ChainAdapter; @@ -24,6 +25,8 @@ use Symfony\Component\Cache\Tests\Fixtures\ExternalAdapter; */ class ChainAdapterTest extends AdapterTestCase { + use ForwardCompatTestTrait; + public function createCachePool($defaultLifetime = 0, $testMethod = null) { if ('testGetMetadata' === $testMethod) { @@ -33,21 +36,17 @@ class ChainAdapterTest extends AdapterTestCase return new ChainAdapter([new ArrayAdapter($defaultLifetime), new ExternalAdapter(), new FilesystemAdapter('', $defaultLifetime)], $defaultLifetime); } - /** - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage At least one adapter must be specified. - */ public function testEmptyAdaptersException() { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('At least one adapter must be specified.'); new ChainAdapter([]); } - /** - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage The class "stdClass" does not implement - */ public function testInvalidAdapterException() { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The class "stdClass" does not implement'); new ChainAdapter([new \stdClass()]); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/MaxIdLengthAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/MaxIdLengthAdapterTest.php index 5da80db0de..cd51a35bad 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/MaxIdLengthAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/MaxIdLengthAdapterTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Cache\Tests\Adapter; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Cache\Adapter\AbstractAdapter; class MaxIdLengthAdapterTest extends TestCase { + use ForwardCompatTestTrait; + public function testLongKey() { $cache = $this->getMockBuilder(MaxIdLengthAdapter::class) @@ -62,12 +65,10 @@ class MaxIdLengthAdapterTest extends TestCase $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 40)]))); } - /** - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Namespace must be 26 chars max, 40 given ("----------------------------------------") - */ public function testTooLongNamespace() { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Namespace must be 26 chars max, 40 given ("----------------------------------------")'); $cache = $this->getMockBuilder(MaxIdLengthAdapter::class) ->setConstructorArgs([str_repeat('-', 40)]) ->getMock(); diff --git a/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php index 46cebe599b..2c1edbbb32 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php @@ -67,11 +67,11 @@ class MemcachedAdapterTest extends AdapterTestCase /** * @dataProvider provideBadOptions - * @expectedException \ErrorException - * @expectedExceptionMessage constant(): Couldn't find constant Memcached:: */ public function testBadOptions($name, $value) { + $this->expectException('ErrorException'); + $this->expectExceptionMessage('constant(): Couldn\'t find constant Memcached::'); MemcachedAdapter::createConnection([], [$name => $value]); } @@ -97,12 +97,10 @@ class MemcachedAdapterTest extends AdapterTestCase $this->assertSame(1, $client->getOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE)); } - /** - * @expectedException \Symfony\Component\Cache\Exception\CacheException - * @expectedExceptionMessage MemcachedAdapter: "serializer" option must be "php" or "igbinary". - */ public function testOptionSerializer() { + $this->expectException('Symfony\Component\Cache\Exception\CacheException'); + $this->expectExceptionMessage('MemcachedAdapter: "serializer" option must be "php" or "igbinary".'); if (!\Memcached::HAVE_JSON) { $this->markTestSkipped('Memcached::HAVE_JSON required'); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php index 4e9970cd92..c3a41b5107 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Cache\Tests\Adapter; use Psr\Cache\CacheItemInterface; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Component\Cache\Adapter\ProxyAdapter; @@ -22,6 +23,8 @@ use Symfony\Component\Cache\CacheItem; */ class ProxyAdapterTest extends AdapterTestCase { + use ForwardCompatTestTrait; + protected $skippedTests = [ 'testDeferredSaveWithoutCommit' => 'Assumes a shared cache which ArrayAdapter is not.', 'testSaveWithoutExpire' => 'Assumes a shared cache which ArrayAdapter is not.', @@ -37,12 +40,10 @@ class ProxyAdapterTest extends AdapterTestCase return new ProxyAdapter(new ArrayAdapter(), '', $defaultLifetime); } - /** - * @expectedException \Exception - * @expectedExceptionMessage OK bar - */ public function testProxyfiedItem() { + $this->expectException('Exception'); + $this->expectExceptionMessage('OK bar'); $item = new CacheItem(); $pool = new ProxyAdapter(new TestingArrayAdapter($item)); diff --git a/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterSentinelTest.php b/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterSentinelTest.php index 96c942654d..8706408050 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterSentinelTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterSentinelTest.php @@ -31,12 +31,10 @@ class RedisAdapterSentinelTest extends AbstractRedisAdapterTest self::$redis = AbstractAdapter::createConnection('redis:?host['.str_replace(' ', ']&host[', $hosts).']', ['redis_sentinel' => $service]); } - /** - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid Redis DSN: cannot use both redis_cluster and redis_sentinel at the same time - */ public function testInvalidDSNHasBothClusterAndSentinel() { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid Redis DSN: cannot use both redis_cluster and redis_sentinel at the same time'); $dsn = 'redis:?host[redis1]&host[redis2]&host[redis3]&redis_cluster=1&redis_sentinel=mymaster'; RedisAdapter::createConnection($dsn); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterTest.php index f11896bcd9..f6b2df2f0a 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterTest.php @@ -66,11 +66,11 @@ class RedisAdapterTest extends AbstractRedisAdapterTest /** * @dataProvider provideFailedCreateConnection - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Redis connection failed */ public function testFailedCreateConnection($dsn) { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Redis connection failed'); RedisAdapter::createConnection($dsn); } @@ -85,11 +85,11 @@ class RedisAdapterTest extends AbstractRedisAdapterTest /** * @dataProvider provideInvalidCreateConnection - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid Redis DSN */ public function testInvalidCreateConnection($dsn) { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid Redis DSN'); RedisAdapter::createConnection($dsn); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/RedisClusterAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/RedisClusterAdapterTest.php index 78a4775805..bea187a5d8 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/RedisClusterAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/RedisClusterAdapterTest.php @@ -42,11 +42,11 @@ class RedisClusterAdapterTest extends AbstractRedisAdapterTest /** * @dataProvider provideFailedCreateConnection - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Redis connection failed */ public function testFailedCreateConnection($dsn) { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Redis connection failed'); RedisAdapter::createConnection($dsn); } diff --git a/src/Symfony/Component/Cache/Tests/CacheItemTest.php b/src/Symfony/Component/Cache/Tests/CacheItemTest.php index 0e3f4b9a73..706d9ef377 100644 --- a/src/Symfony/Component/Cache/Tests/CacheItemTest.php +++ b/src/Symfony/Component/Cache/Tests/CacheItemTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Cache\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Cache\CacheItem; class CacheItemTest extends TestCase { + use ForwardCompatTestTrait; + public function testValidKey() { $this->assertSame('foo', CacheItem::validateKey('foo')); @@ -23,11 +26,11 @@ class CacheItemTest extends TestCase /** * @dataProvider provideInvalidKey - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Cache key */ public function testInvalidKey($key) { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Cache key'); CacheItem::validateKey($key); } @@ -69,11 +72,11 @@ class CacheItemTest extends TestCase /** * @dataProvider provideInvalidKey - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Cache tag */ public function testInvalidTag($tag) { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Cache tag'); $item = new CacheItem(); $r = new \ReflectionProperty($item, 'isTaggable'); $r->setAccessible(true); @@ -82,12 +85,10 @@ class CacheItemTest extends TestCase $item->tag($tag); } - /** - * @expectedException \Symfony\Component\Cache\Exception\LogicException - * @expectedExceptionMessage Cache item "foo" comes from a non tag-aware pool: you cannot tag it. - */ public function testNonTaggableItem() { + $this->expectException('Symfony\Component\Cache\Exception\LogicException'); + $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->setAccessible(true); diff --git a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPassTest.php b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPassTest.php index 7a175c17e9..85b7e64b1c 100644 --- a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPassTest.php +++ b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPassTest.php @@ -130,12 +130,10 @@ class CachePoolPassTest extends TestCase $this->assertSame('+naTpPa4Sm', $cachePool->getArgument(1)); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid "cache.pool" tag for service "app.cache_pool": accepted attributes are - */ public function testThrowsExceptionWhenCachePoolTagHasUnknownAttributes() { + $this->expectException('InvalidArgumentException'); + $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'); diff --git a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php index 128ee243c6..2a1ab49b64 100644 --- a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php +++ b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php @@ -56,12 +56,10 @@ class CachePoolPrunerPassTest extends TestCase $this->assertCount($aliasesBefore, $container->getAliases()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Class "Symfony\Component\Cache\Tests\DependencyInjection\NotFound" used for service "pool.not-found" cannot be found. - */ public function testCompilerPassThrowsOnInvalidDefinitionClass() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $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'); diff --git a/src/Symfony/Component/Cache/Tests/Marshaller/DefaultMarshallerTest.php b/src/Symfony/Component/Cache/Tests/Marshaller/DefaultMarshallerTest.php index daa1fd19f4..aa0e0221d4 100644 --- a/src/Symfony/Component/Cache/Tests/Marshaller/DefaultMarshallerTest.php +++ b/src/Symfony/Component/Cache/Tests/Marshaller/DefaultMarshallerTest.php @@ -50,33 +50,29 @@ class DefaultMarshallerTest extends TestCase $this->assertSame(0, $marshaller->unmarshall(igbinary_serialize(0))); } - /** - * @expectedException \DomainException - * @expectedExceptionMessage Class not found: NotExistingClass - */ public function testNativeUnserializeNotFoundClass() { + $this->expectException('DomainException'); + $this->expectExceptionMessage('Class not found: NotExistingClass'); $marshaller = new DefaultMarshaller(); $marshaller->unmarshall('O:16:"NotExistingClass":0:{}'); } /** * @requires extension igbinary - * @expectedException \DomainException - * @expectedExceptionMessage Class not found: NotExistingClass */ public function testIgbinaryUnserializeNotFoundClass() { + $this->expectException('DomainException'); + $this->expectExceptionMessage('Class not found: NotExistingClass'); $marshaller = new DefaultMarshaller(); $marshaller->unmarshall(rawurldecode('%00%00%00%02%17%10NotExistingClass%14%00')); } - /** - * @expectedException \DomainException - * @expectedExceptionMessage unserialize(): Error at offset 0 of 3 bytes - */ public function testNativeUnserializeInvalid() { + $this->expectException('DomainException'); + $this->expectExceptionMessage('unserialize(): Error at offset 0 of 3 bytes'); $marshaller = new DefaultMarshaller(); set_error_handler(function () { return false; }); try { @@ -88,11 +84,11 @@ class DefaultMarshallerTest extends TestCase /** * @requires extension igbinary - * @expectedException \DomainException - * @expectedExceptionMessage igbinary_unserialize_zval: unknown type '61', position 5 */ public function testIgbinaryUnserializeInvalid() { + $this->expectException('DomainException'); + $this->expectExceptionMessage('igbinary_unserialize_zval: unknown type \'61\', position 5'); $marshaller = new DefaultMarshaller(); set_error_handler(function () { return false; }); try { diff --git a/src/Symfony/Component/Cache/Tests/Traits/TagAwareTestTrait.php b/src/Symfony/Component/Cache/Tests/Traits/TagAwareTestTrait.php index 6fda3e1ad2..c27213e03b 100644 --- a/src/Symfony/Component/Cache/Tests/Traits/TagAwareTestTrait.php +++ b/src/Symfony/Component/Cache/Tests/Traits/TagAwareTestTrait.php @@ -20,11 +20,9 @@ use Symfony\Component\Cache\CacheItem; */ trait TagAwareTestTrait { - /** - * @expectedException \Psr\Cache\InvalidArgumentException - */ public function testInvalidTag() { + $this->expectException('Psr\Cache\InvalidArgumentException'); $pool = $this->createCachePool(); $item = $pool->getItem('foo'); $item->tag(':'); diff --git a/src/Symfony/Component/Config/Tests/ConfigCacheFactoryTest.php b/src/Symfony/Component/Config/Tests/ConfigCacheFactoryTest.php index a1dd169eca..d61582b652 100644 --- a/src/Symfony/Component/Config/Tests/ConfigCacheFactoryTest.php +++ b/src/Symfony/Component/Config/Tests/ConfigCacheFactoryTest.php @@ -16,11 +16,9 @@ use Symfony\Component\Config\ConfigCacheFactory; class ConfigCacheFactoryTest extends TestCase { - /** - * @expectedException \TypeError - */ public function testCacheWithInvalidCallback() { + $this->expectException('TypeError'); $cacheFactory = new ConfigCacheFactory(true); $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 0df24b8cc1..bc49f19cf8 100644 --- a/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php @@ -21,31 +21,25 @@ class ArrayNodeTest extends TestCase { use ForwardCompatTestTrait; - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException - */ public function testNormalizeThrowsExceptionWhenFalseIsNotAllowed() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); $node = new ArrayNode('root'); $node->normalize(false); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage Unrecognized option "foo" under "root" - */ public function testExceptionThrownOnUnrecognizedChild() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('Unrecognized option "foo" under "root"'); $node = new ArrayNode('root'); $node->normalize(['foo' => 'bar']); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage Did you mean "alpha1", "alpha2"? - */ public function testNormalizeWithProposals() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('Did you mean "alpha1", "alpha2"?'); $node = new ArrayNode('root'); $node->addChild(new ArrayNode('alpha1')); $node->addChild(new ArrayNode('alpha2')); @@ -53,12 +47,10 @@ class ArrayNodeTest extends TestCase $node->normalize(['alpha3' => 'foo']); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage Available options are "alpha1", "alpha2". - */ public function testNormalizeWithoutProposals() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('Available options are "alpha1", "alpha2".'); $node = new ArrayNode('root'); $node->addChild(new ArrayNode('alpha1')); $node->addChild(new ArrayNode('alpha2')); @@ -204,24 +196,20 @@ class ArrayNodeTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Child nodes must be named. - */ public function testAddChildEmptyName() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Child nodes must be named.'); $node = new ArrayNode('root'); $childNode = new ArrayNode(''); $node->addChild($childNode); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage A child node named "foo" already exists. - */ public function testAddChildNameAlreadyExists() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('A child node named "foo" already exists.'); $node = new ArrayNode('root'); $childNode = new ArrayNode('foo'); @@ -231,12 +219,10 @@ class ArrayNodeTest extends TestCase $node->addChild($childNodeWithSameName); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage The node at path "foo" has no default value. - */ public function testGetDefaultValueWithoutDefaultValue() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('The node at path "foo" has no default value.'); $node = new ArrayNode('foo'); $node->getDefaultValue(); } diff --git a/src/Symfony/Component/Config/Tests/Definition/BaseNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/BaseNodeTest.php index 68fa1c7d31..ea2ed639ff 100644 --- a/src/Symfony/Component/Config/Tests/Definition/BaseNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/BaseNodeTest.php @@ -26,10 +26,7 @@ class BaseNodeTest extends TestCase $constructorArgs[] = $params[0]; if (isset($params[1])) { - // Handle old PHPUnit version for PHP 5.5 - $parent = method_exists($this, 'createMock') - ? $this->createMock(NodeInterface::class) - : $this->getMock(NodeInterface::class); + $parent = $this->createMock(NodeInterface::class); $parent->method('getPath')->willReturn($params[1]); $constructorArgs[] = $parent; diff --git a/src/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.php index bfa2fd3e28..df10377d4a 100644 --- a/src/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Config\Tests\Definition; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Definition\BooleanNode; class BooleanNodeTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getValidValues */ @@ -48,10 +51,10 @@ class BooleanNodeTest extends TestCase /** * @dataProvider getInvalidValues - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); $node = new BooleanNode('test'); $node->normalize($value); } diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php index 0c414a9b9d..db819d2e5f 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Config\Tests\Definition\Builder; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\BooleanNodeDefinition; use Symfony\Component\Config\Definition\Builder\NodeDefinition; @@ -21,6 +22,8 @@ use Symfony\Component\Config\Definition\Processor; class ArrayNodeDefinitionTest extends TestCase { + use ForwardCompatTestTrait; + public function testAppendingSomeNode() { $parent = new ArrayNodeDefinition('root'); @@ -38,11 +41,11 @@ class ArrayNodeDefinitionTest extends TestCase } /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException * @dataProvider providePrototypeNodeSpecificCalls */ public function testPrototypeNodeSpecificOption($method, $args) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); $node = new ArrayNodeDefinition('root'); $node->{$method}(...$args); @@ -61,11 +64,9 @@ class ArrayNodeDefinitionTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException - */ public function testConcreteNodeSpecificOption() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); $node = new ArrayNodeDefinition('root'); $node ->addDefaultsIfNotSet() @@ -74,11 +75,9 @@ class ArrayNodeDefinitionTest extends TestCase $node->getNode(); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException - */ public function testPrototypeNodesCantHaveADefaultValueWhenUsingDefaultChildren() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); $node = new ArrayNodeDefinition('root'); $node ->defaultValue([]) @@ -319,12 +318,10 @@ class ArrayNodeDefinitionTest extends TestCase $this->addToAssertionCount(1); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The path "root" should have at least 1 element(s) defined. - */ public function testCannotBeEmpty() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('The path "root" should have at least 1 element(s) defined.'); $node = new ArrayNodeDefinition('root'); $node ->cannotBeEmpty() @@ -347,12 +344,10 @@ class ArrayNodeDefinitionTest extends TestCase $this->assertSame('The "root.foo" node is deprecated.', $deprecatedNode->getDeprecationMessage($deprecatedNode->getName(), $deprecatedNode->getPath())); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException - * @expectedExceptionMessage ->cannotBeEmpty() is not applicable to concrete nodes at path "root" - */ public function testCannotBeEmptyOnConcreteNode() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); + $this->expectExceptionMessage('->cannotBeEmpty() is not applicable to concrete nodes at path "root"'); $node = new ArrayNodeDefinition('root'); $node->cannotBeEmpty(); diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php index c0d347f3d3..dd605b80b0 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php @@ -12,16 +12,17 @@ namespace Symfony\Component\Config\Tests\Definition\Builder; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Definition\Builder\BooleanNodeDefinition; class BooleanNodeDefinitionTest extends TestCase { - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException - * @expectedExceptionMessage ->cannotBeEmpty() is not applicable to BooleanNodeDefinition. - */ + use ForwardCompatTestTrait; + public function testCannotBeEmptyThrowsAnException() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); + $this->expectExceptionMessage('->cannotBeEmpty() is not applicable to BooleanNodeDefinition.'); $def = new BooleanNodeDefinition('foo'); $def->cannotBeEmpty(); } diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/EnumNodeDefinitionTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/EnumNodeDefinitionTest.php index 26f8586dcb..6247bfaea3 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/EnumNodeDefinitionTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/EnumNodeDefinitionTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Config\Tests\Definition\Builder; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Definition\Builder\EnumNodeDefinition; class EnumNodeDefinitionTest extends TestCase { + use ForwardCompatTestTrait; + public function testWithOneValue() { $def = new EnumNodeDefinition('foo'); @@ -34,22 +37,18 @@ class EnumNodeDefinitionTest extends TestCase $this->assertEquals(['foo'], $node->getValues()); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage You must call ->values() on enum nodes. - */ public function testNoValuesPassed() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('You must call ->values() on enum nodes.'); $def = new EnumNodeDefinition('foo'); $def->getNode(); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage ->values() must be called with at least one value. - */ public function testWithNoValues() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('->values() must be called with at least one value.'); $def = new EnumNodeDefinition('foo'); $def->values([]); } diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/ExprBuilderTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/ExprBuilderTest.php index 9486d4f90b..56234527e8 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/ExprBuilderTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/ExprBuilderTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Config\Tests\Definition\Builder; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Definition\Builder\TreeBuilder; class ExprBuilderTest extends TestCase { + use ForwardCompatTestTrait; + public function testAlwaysExpression() { $test = $this->getTestBuilder() @@ -164,11 +167,9 @@ class ExprBuilderTest extends TestCase yield [['value'], ['value']]; } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - */ public function testThenInvalid() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $test = $this->getTestBuilder() ->ifString() ->thenInvalid('Invalid value') @@ -185,21 +186,17 @@ class ExprBuilderTest extends TestCase $this->assertEquals([], $this->finalizeTestBuilder($test)); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage You must specify an if part. - */ public function testEndIfPartNotSpecified() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('You must specify an if part.'); $this->getTestBuilder()->end(); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage You must specify a then part. - */ public function testEndThenPartNotSpecified() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('You must specify a then part.'); $builder = $this->getTestBuilder(); $builder->ifPart = 'test'; $builder->end(); diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/NodeBuilderTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/NodeBuilderTest.php index cd77dd702b..cf91b69216 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/NodeBuilderTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/NodeBuilderTest.php @@ -12,25 +12,24 @@ namespace Symfony\Component\Config\Tests\Definition\Builder; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Definition\Builder\NodeBuilder as BaseNodeBuilder; use Symfony\Component\Config\Definition\Builder\VariableNodeDefinition as BaseVariableNodeDefinition; class NodeBuilderTest extends TestCase { - /** - * @expectedException \RuntimeException - */ + use ForwardCompatTestTrait; + public function testThrowsAnExceptionWhenTryingToCreateANonRegisteredNodeType() { + $this->expectException('RuntimeException'); $builder = new BaseNodeBuilder(); $builder->node('', 'foobar'); } - /** - * @expectedException \RuntimeException - */ public function testThrowsAnExceptionWhenTheNodeClassIsNotFound() { + $this->expectException('RuntimeException'); $builder = new BaseNodeBuilder(); $builder ->setNodeClass('noclasstype', '\\foo\\bar\\noclass') diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.php index 31342503d8..cfd71f4196 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.php @@ -12,48 +12,43 @@ namespace Symfony\Component\Config\Tests\Definition\Builder; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Definition\Builder\FloatNodeDefinition; use Symfony\Component\Config\Definition\Builder\IntegerNodeDefinition; use Symfony\Component\Config\Definition\Builder\IntegerNodeDefinition as NumericNodeDefinition; class NumericNodeDefinitionTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage You cannot define a min(4) as you already have a max(3) - */ + use ForwardCompatTestTrait; + public function testIncoherentMinAssertion() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('You cannot define a min(4) as you already have a max(3)'); $def = new NumericNodeDefinition('foo'); $def->max(3)->min(4); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage You cannot define a max(2) as you already have a min(3) - */ public function testIncoherentMaxAssertion() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('You cannot define a max(2) as you already have a min(3)'); $node = new NumericNodeDefinition('foo'); $node->min(3)->max(2); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The value 4 is too small for path "foo". Should be greater than or equal to 5 - */ public function testIntegerMinAssertion() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $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); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The value 4 is too big for path "foo". Should be less than or equal to 3 - */ public function testIntegerMaxAssertion() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $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); } @@ -65,22 +60,18 @@ class NumericNodeDefinitionTest extends TestCase $this->assertEquals(4, $node->finalize(4)); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The value 400 is too small for path "foo". Should be greater than or equal to 500 - */ public function testFloatMinAssertion() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $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); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The value 4.3 is too big for path "foo". Should be less than or equal to 0.3 - */ public function testFloatMaxAssertion() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $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); } @@ -92,12 +83,10 @@ class NumericNodeDefinitionTest extends TestCase $this->assertEquals(4.5, $node->finalize(4.5)); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException - * @expectedExceptionMessage ->cannotBeEmpty() is not applicable to NumericNodeDefinition. - */ public function testCannotBeEmptyThrowsAnException() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); + $this->expectExceptionMessage('->cannotBeEmpty() is not applicable to NumericNodeDefinition.'); $def = new NumericNodeDefinition('foo'); $def->cannotBeEmpty(); } diff --git a/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php index 8d679be980..5ab558d917 100644 --- a/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php @@ -12,22 +12,23 @@ namespace Symfony\Component\Config\Tests\Definition; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Definition\EnumNode; class EnumNodeTest extends TestCase { + use ForwardCompatTestTrait; + public function testFinalizeValue() { $node = new EnumNode('foo', null, ['foo', 'bar']); $this->assertSame('foo', $node->finalize('foo')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage $values must contain at least one element. - */ public function testConstructionWithNoValues() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('$values must contain at least one element.'); new EnumNode('foo', null, []); } @@ -49,12 +50,10 @@ class EnumNodeTest extends TestCase $this->assertSame('foo', $node->finalize('foo')); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The value "foobar" is not allowed for path "foo". Permissible values: "foo", "bar" - */ public function testFinalizeWithInvalidValue() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('The value "foobar" is not allowed for path "foo". Permissible values: "foo", "bar"'); $node = new EnumNode('foo', null, ['foo', 'bar']); $node->finalize('foobar'); } diff --git a/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php index 8268fe83ba..16b570930d 100644 --- a/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Config\Tests\Definition; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Definition\FloatNode; class FloatNodeTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getValidValues */ @@ -54,10 +57,10 @@ class FloatNodeTest extends TestCase /** * @dataProvider getInvalidValues - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); $node = new FloatNode('test'); $node->normalize($value); } diff --git a/src/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.php index b4c17e1cb9..b7fb73caf6 100644 --- a/src/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Config\Tests\Definition; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Definition\IntegerNode; class IntegerNodeTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getValidValues */ @@ -49,10 +52,10 @@ class IntegerNodeTest extends TestCase /** * @dataProvider getInvalidValues - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); $node = new IntegerNode('test'); $node->normalize($value); } diff --git a/src/Symfony/Component/Config/Tests/Definition/MergeTest.php b/src/Symfony/Component/Config/Tests/Definition/MergeTest.php index b88205d7b5..e2fb1163c0 100644 --- a/src/Symfony/Component/Config/Tests/Definition/MergeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/MergeTest.php @@ -12,15 +12,16 @@ namespace Symfony\Component\Config\Tests\Definition; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Definition\Builder\TreeBuilder; class MergeTest extends TestCase { - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\ForbiddenOverwriteException - */ + use ForwardCompatTestTrait; + public function testForbiddenOverwrite() { + $this->expectException('Symfony\Component\Config\Definition\Exception\ForbiddenOverwriteException'); $tb = new TreeBuilder('root', 'array'); $tree = $tb ->getRootNode() @@ -92,11 +93,9 @@ class MergeTest extends TestCase ], $tree->merge($a, $b)); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - */ public function testDoesNotAllowNewKeysInSubsequentConfigs() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $tb = new TreeBuilder('root', 'array'); $tree = $tb ->getRootNode() diff --git a/src/Symfony/Component/Config/Tests/Definition/NormalizationTest.php b/src/Symfony/Component/Config/Tests/Definition/NormalizationTest.php index ebd9a75b3c..9f5abc1672 100644 --- a/src/Symfony/Component/Config/Tests/Definition/NormalizationTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/NormalizationTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Config\Tests\Definition; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\NodeInterface; class NormalizationTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getEncoderTests */ @@ -169,12 +172,10 @@ class NormalizationTest extends TestCase return array_map(function ($v) { return [$v]; }, $configs); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The attribute "id" must be set for path "root.thing". - */ public function testNonAssociativeArrayThrowsExceptionIfAttributeNotSet() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('The attribute "id" must be set for path "root.thing".'); $denormalized = [ 'thing' => [ ['foo', 'bar'], ['baz', 'qux'], diff --git a/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php index 36f25667ce..e59421211d 100644 --- a/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php @@ -77,10 +77,10 @@ class ScalarNodeTest extends TestCase /** * @dataProvider getInvalidValues - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); $node = new ScalarNode('test'); $node->normalize($value); } @@ -143,12 +143,12 @@ class ScalarNodeTest extends TestCase /** * @dataProvider getEmptyValues - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException * * @param mixed $value */ public function testNotAllowedEmptyValuesThrowException($value) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $node = new ScalarNode('test'); $node->setAllowEmptyValue(false); $node->finalize($value); diff --git a/src/Symfony/Component/Config/Tests/FileLocatorTest.php b/src/Symfony/Component/Config/Tests/FileLocatorTest.php index d4299111cf..b2810402c1 100644 --- a/src/Symfony/Component/Config/Tests/FileLocatorTest.php +++ b/src/Symfony/Component/Config/Tests/FileLocatorTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Config\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\FileLocator; class FileLocatorTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getIsAbsolutePathTests */ @@ -86,33 +89,27 @@ class FileLocatorTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\Config\Exception\FileLocatorFileNotFoundException - * @expectedExceptionMessage The file "foobar.xml" does not exist - */ public function testLocateThrowsAnExceptionIfTheFileDoesNotExists() { + $this->expectException('Symfony\Component\Config\Exception\FileLocatorFileNotFoundException'); + $this->expectExceptionMessage('The file "foobar.xml" does not exist'); $loader = new FileLocator([__DIR__.'/Fixtures']); $loader->locate('foobar.xml', __DIR__); } - /** - * @expectedException \Symfony\Component\Config\Exception\FileLocatorFileNotFoundException - */ public function testLocateThrowsAnExceptionIfTheFileDoesNotExistsInAbsolutePath() { + $this->expectException('Symfony\Component\Config\Exception\FileLocatorFileNotFoundException'); $loader = new FileLocator([__DIR__.'/Fixtures']); $loader->locate(__DIR__.'/Fixtures/foobar.xml', __DIR__); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage An empty file name is not valid to be located. - */ public function testLocateEmpty() { + $this->expectException('InvalidArgumentException'); + $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 daff5288ef..d139d3e2f3 100644 --- a/src/Symfony/Component/Config/Tests/Loader/DelegatingLoaderTest.php +++ b/src/Symfony/Component/Config/Tests/Loader/DelegatingLoaderTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Config\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Loader\DelegatingLoader; use Symfony\Component\Config\Loader\LoaderResolver; class DelegatingLoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $loader = new DelegatingLoader($resolver = new LoaderResolver()); @@ -56,11 +59,9 @@ class DelegatingLoaderTest extends TestCase $loader->load('foo'); } - /** - * @expectedException \Symfony\Component\Config\Exception\LoaderLoadException - */ public function testLoadThrowsAnExceptionIfTheResourceCannotBeLoaded() { + $this->expectException('Symfony\Component\Config\Exception\LoaderLoadException'); $loader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock(); $loader->expects($this->once())->method('supports')->willReturn(false); $resolver = new LoaderResolver([$loader]); diff --git a/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php b/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php index 9d43a2c4ef..a6b825632f 100644 --- a/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php +++ b/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Config\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Loader\Loader; class LoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testGetSetResolver() { $resolver = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderResolverInterface')->getMock(); @@ -43,11 +46,9 @@ class LoaderTest extends TestCase $this->assertSame($resolvedLoader, $loader->resolve('foo.xml'), '->resolve() finds a loader'); } - /** - * @expectedException \Symfony\Component\Config\Exception\LoaderLoadException - */ public function testResolveWhenResolverCannotFindLoader() { + $this->expectException('Symfony\Component\Config\Exception\LoaderLoadException'); $resolver = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderResolverInterface')->getMock(); $resolver->expects($this->once()) ->method('resolve') diff --git a/src/Symfony/Component/Config/Tests/Resource/ClassExistenceResourceTest.php b/src/Symfony/Component/Config/Tests/Resource/ClassExistenceResourceTest.php index 5612e7ca24..8807d9fb0e 100644 --- a/src/Symfony/Component/Config/Tests/Resource/ClassExistenceResourceTest.php +++ b/src/Symfony/Component/Config/Tests/Resource/ClassExistenceResourceTest.php @@ -13,12 +13,15 @@ namespace Symfony\Component\Config\Tests\Resource; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\Warning; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Resource\ClassExistenceResource; use Symfony\Component\Config\Tests\Fixtures\BadParent; use Symfony\Component\Config\Tests\Fixtures\Resource\ConditionalClass; class ClassExistenceResourceTest extends TestCase { + use ForwardCompatTestTrait; + public function testToString() { $res = new ClassExistenceResource('BarClass'); @@ -86,12 +89,10 @@ EOF $this->assertTrue($res->isFresh(time())); } - /** - * @expectedException \ReflectionException - * @expectedExceptionMessage Class Symfony\Component\Config\Tests\Fixtures\MissingParent not found - */ public function testBadParentWithNoTimestamp() { + $this->expectException('ReflectionException'); + $this->expectExceptionMessage('Class Symfony\Component\Config\Tests\Fixtures\MissingParent not found'); if (\PHP_VERSION_ID >= 70400) { throw new Warning('PHP 7.4 breaks this test, see https://bugs.php.net/78351.'); } diff --git a/src/Symfony/Component/Config/Tests/Resource/DirectoryResourceTest.php b/src/Symfony/Component/Config/Tests/Resource/DirectoryResourceTest.php index 6e86f9142d..2bdd3849b2 100644 --- a/src/Symfony/Component/Config/Tests/Resource/DirectoryResourceTest.php +++ b/src/Symfony/Component/Config/Tests/Resource/DirectoryResourceTest.php @@ -66,12 +66,10 @@ class DirectoryResourceTest extends TestCase $this->assertEquals('bar', $resource->getPattern()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /The directory ".*" does not exist./ - */ public function testResourceDoesNotExist() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The directory ".*" does not exist./'); $resource = new DirectoryResource('/____foo/foobar'.mt_rand(1, 999999)); } diff --git a/src/Symfony/Component/Config/Tests/Resource/FileResourceTest.php b/src/Symfony/Component/Config/Tests/Resource/FileResourceTest.php index 091d9630e0..8aa0e4b3ac 100644 --- a/src/Symfony/Component/Config/Tests/Resource/FileResourceTest.php +++ b/src/Symfony/Component/Config/Tests/Resource/FileResourceTest.php @@ -56,12 +56,10 @@ class FileResourceTest extends TestCase $this->assertSame(realpath($this->file), (string) $this->resource); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /The file ".*" does not exist./ - */ public function testResourceDoesNotExist() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The file ".*" does not exist./'); $resource = new FileResource('/____foo/foobar'.mt_rand(1, 999999)); } diff --git a/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php b/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php index 8c5d0a957f..3f54a1e68e 100644 --- a/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php +++ b/src/Symfony/Component/Config/Tests/Util/XmlUtilsTest.php @@ -65,12 +65,10 @@ class XmlUtilsTest extends TestCase $this->assertSame([], libxml_get_errors()); } - /** - * @expectedException \Symfony\Component\Config\Util\Exception\InvalidXmlException - * @expectedExceptionMessage The XML is not valid - */ public function testParseWithInvalidValidatorCallable() { + $this->expectException('Symfony\Component\Config\Util\Exception\InvalidXmlException'); + $this->expectExceptionMessage('The XML is not valid'); $fixtures = __DIR__.'/../Fixtures/Util/'; $mock = $this->getMockBuilder(__NAMESPACE__.'\Validator')->getMock(); diff --git a/src/Symfony/Component/Console/Tests/ApplicationTest.php b/src/Symfony/Component/Console/Tests/ApplicationTest.php index 0acdb48805..281222d8d6 100644 --- a/src/Symfony/Component/Console/Tests/ApplicationTest.php +++ b/src/Symfony/Component/Console/Tests/ApplicationTest.php @@ -203,12 +203,10 @@ class ApplicationTest extends TestCase $this->assertEquals([$foo, $foo1], [$commands['foo:bar'], $commands['foo:bar1']], '->addCommands() registers an array of commands'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Command class "Foo5Command" is not correctly initialized. You probably forgot to call the parent constructor. - */ public function testAddCommandWithEmptyConstructor() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Command class "Foo5Command" is not correctly initialized. You probably forgot to call the parent constructor.'); $application = new Application(); $application->add(new \Foo5Command()); } @@ -271,12 +269,10 @@ class ApplicationTest extends TestCase $this->assertEmpty($tester->getDisplay(true)); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - * @expectedExceptionMessage The command "foofoo" does not exist. - */ public function testGetInvalidCommand() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); + $this->expectExceptionMessage('The command "foofoo" does not exist.'); $application = new Application(); $application->get('foofoo'); } @@ -330,22 +326,18 @@ class ApplicationTest extends TestCase $this->assertEquals('test-ambiguous', $application->find('test')->getName()); } - /** - * @expectedException \Symfony\Component\Console\Exception\NamespaceNotFoundException - * @expectedExceptionMessage There are no commands defined in the "bar" namespace. - */ public function testFindInvalidNamespace() { + $this->expectException('Symfony\Component\Console\Exception\NamespaceNotFoundException'); + $this->expectExceptionMessage('There are no commands defined in the "bar" namespace.'); $application = new Application(); $application->findNamespace('bar'); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - * @expectedExceptionMessage Command "foo1" is not defined - */ public function testFindUniqueNameButNamespaceName() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); + $this->expectExceptionMessage('Command "foo1" is not defined'); $application = new Application(); $application->add(new \FooCommand()); $application->add(new \Foo1Command()); @@ -388,12 +380,10 @@ class ApplicationTest extends TestCase $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('FoO:BaR'), '->find() will fallback to case insensitivity'); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - * @expectedExceptionMessage Command "FoO:BaR" is ambiguous - */ public function testFindCaseInsensitiveSuggestions() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); + $this->expectExceptionMessage('Command "FoO:BaR" is ambiguous'); $application = new Application(); $application->add(new \FooSameCaseLowercaseCommand()); $application->add(new \FooSameCaseUppercaseCommand()); @@ -481,12 +471,12 @@ class ApplicationTest extends TestCase } /** - * @dataProvider provideInvalidCommandNamesSingle - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - * @expectedExceptionMessage Did you mean this + * @dataProvider provideInvalidCommandNamesSingle */ public function testFindAlternativeExceptionMessageSingle($name) { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); + $this->expectExceptionMessage('Did you mean this'); $application = new Application(); $application->add(new \Foo3Command()); $application->find($name); @@ -709,12 +699,10 @@ class ApplicationTest extends TestCase $this->assertEquals('foo:sublong', $application->findNamespace('f:sub')); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - * @expectedExceptionMessage Command "foo::bar" is not defined. - */ public function testFindWithDoubleColonInNameThrowsException() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); + $this->expectExceptionMessage('Command "foo::bar" is not defined.'); $application = new Application(); $application->add(new \FooCommand()); $application->add(new \Foo4Command()); @@ -1120,12 +1108,10 @@ class ApplicationTest extends TestCase $this->assertTrue($passedRightValue, '-> exit code 1 was passed in the console.terminate event'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage An option with shortcut "e" already exists. - */ public function testAddingOptionWithDuplicateShortcut() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('An option with shortcut "e" already exists.'); $dispatcher = new EventDispatcher(); $application = new Application(); $application->setAutoExit(false); @@ -1148,11 +1134,11 @@ class ApplicationTest extends TestCase } /** - * @expectedException \LogicException * @dataProvider getAddingAlreadySetDefinitionElementData */ public function testAddingAlreadySetDefinitionElementData($def) { + $this->expectException('LogicException'); $application = new Application(); $application->setAutoExit(false); $application->setCatchExceptions(false); @@ -1301,12 +1287,10 @@ class ApplicationTest extends TestCase $this->assertEquals('before.foo.after.'.PHP_EOL, $tester->getDisplay()); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage error - */ public function testRunWithExceptionAndDispatcher() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('error'); $application = new Application(); $application->setDispatcher($this->getDispatcher()); $application->setAutoExit(false); @@ -1446,12 +1430,10 @@ class ApplicationTest extends TestCase } } - /** - * @expectedException \LogicException - * @expectedExceptionMessage error - */ public function testRunWithErrorAndDispatcher() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('error'); $application = new Application(); $application->setDispatcher($this->getDispatcher()); $application->setAutoExit(false); @@ -1677,11 +1659,9 @@ class ApplicationTest extends TestCase $this->assertSame(['lazy:alias', 'lazy:alias2'], $command->getAliases()); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - */ public function testGetDisabledLazyCommand() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); $application = new Application(); $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }])); $application->get('disabled'); @@ -1747,12 +1727,10 @@ class ApplicationTest extends TestCase } } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage foo - */ public function testThrowingErrorListener() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('foo'); $dispatcher = $this->getDispatcher(); $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) { throw new \RuntimeException('foo'); diff --git a/src/Symfony/Component/Console/Tests/Command/CommandTest.php b/src/Symfony/Component/Console/Tests/Command/CommandTest.php index fb17c4b460..e771967b46 100644 --- a/src/Symfony/Component/Console/Tests/Command/CommandTest.php +++ b/src/Symfony/Component/Console/Tests/Command/CommandTest.php @@ -43,12 +43,10 @@ class CommandTest extends TestCase $this->assertEquals('foo:bar', $command->getName(), '__construct() takes the command name as its first argument'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage The command defined in "Symfony\Component\Console\Command\Command" cannot have an empty name. - */ public function testCommandNameCannotBeEmpty() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('The command defined in "Symfony\Component\Console\Command\Command" cannot have an empty name.'); (new Application())->add(new Command()); } @@ -210,12 +208,10 @@ class CommandTest extends TestCase $this->assertEquals($formatterHelper->getName(), $command->getHelper('formatter')->getName(), '->getHelper() returns the correct helper'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Cannot retrieve helper "formatter" because there is no HelperSet defined. - */ public function testGetHelperWithoutHelperSet() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Cannot retrieve helper "formatter" because there is no HelperSet defined.'); $command = new \TestCommand(); $command->getHelper('formatter'); } @@ -283,22 +279,18 @@ class CommandTest extends TestCase $this->assertEquals('execute called'.PHP_EOL, $tester->getDisplay(), '->run() does not call the interact() method if the input is not interactive'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage You must override the execute() method in the concrete command class. - */ public function testExecuteMethodNeedsToBeOverridden() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('You must override the execute() method in the concrete command class.'); $command = new Command('foo'); $command->run(new StringInput(''), new NullOutput()); } - /** - * @expectedException \Symfony\Component\Console\Exception\InvalidOptionException - * @expectedExceptionMessage The "--bar" option does not exist. - */ public function testRunWithInvalidOption() { + $this->expectException('Symfony\Component\Console\Exception\InvalidOptionException'); + $this->expectExceptionMessage('The "--bar" option does not exist.'); $command = new \TestCommand(); $tester = new CommandTester($command); $tester->execute(['--bar' => true]); diff --git a/src/Symfony/Component/Console/Tests/CommandLoader/ContainerCommandLoaderTest.php b/src/Symfony/Component/Console/Tests/CommandLoader/ContainerCommandLoaderTest.php index 18d6e77bfb..67625dc6c1 100644 --- a/src/Symfony/Component/Console/Tests/CommandLoader/ContainerCommandLoaderTest.php +++ b/src/Symfony/Component/Console/Tests/CommandLoader/ContainerCommandLoaderTest.php @@ -12,12 +12,15 @@ namespace Symfony\Component\Console\Tests\CommandLoader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\CommandLoader\ContainerCommandLoader; use Symfony\Component\DependencyInjection\ServiceLocator; class ContainerCommandLoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testHas() { $loader = new ContainerCommandLoader(new ServiceLocator([ @@ -41,11 +44,9 @@ class ContainerCommandLoaderTest extends TestCase $this->assertInstanceOf(Command::class, $loader->get('bar')); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - */ public function testGetUnknownCommandThrows() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); (new ContainerCommandLoader(new ServiceLocator([]), []))->get('unknown'); } diff --git a/src/Symfony/Component/Console/Tests/CommandLoader/FactoryCommandLoaderTest.php b/src/Symfony/Component/Console/Tests/CommandLoader/FactoryCommandLoaderTest.php index 7b9ec837e6..f0fd40637e 100644 --- a/src/Symfony/Component/Console/Tests/CommandLoader/FactoryCommandLoaderTest.php +++ b/src/Symfony/Component/Console/Tests/CommandLoader/FactoryCommandLoaderTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Console\Tests\CommandLoader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\CommandLoader\FactoryCommandLoader; class FactoryCommandLoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testHas() { $loader = new FactoryCommandLoader([ @@ -40,11 +43,9 @@ class FactoryCommandLoaderTest extends TestCase $this->assertInstanceOf(Command::class, $loader->get('bar')); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - */ public function testGetUnknownCommandThrows() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); (new FactoryCommandLoader([]))->get('unknown'); } diff --git a/src/Symfony/Component/Console/Tests/DependencyInjection/AddConsoleCommandPassTest.php b/src/Symfony/Component/Console/Tests/DependencyInjection/AddConsoleCommandPassTest.php index a0b66bc178..ea8758a273 100644 --- a/src/Symfony/Component/Console/Tests/DependencyInjection/AddConsoleCommandPassTest.php +++ b/src/Symfony/Component/Console/Tests/DependencyInjection/AddConsoleCommandPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Console\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\CommandLoader\ContainerCommandLoader; use Symfony\Component\Console\DependencyInjection\AddConsoleCommandPass; @@ -24,6 +25,8 @@ use Symfony\Component\DependencyInjection\TypedReference; class AddConsoleCommandPassTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider visibilityProvider */ @@ -118,12 +121,10 @@ class AddConsoleCommandPassTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The service "my-command" tagged "console.command" must not be abstract. - */ public function testProcessThrowAnExceptionIfTheServiceIsAbstract() { + $this->expectException('InvalidArgumentException'); + $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); @@ -136,12 +137,10 @@ class AddConsoleCommandPassTest extends TestCase $container->compile(); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The service "my-command" tagged "console.command" must be a subclass of "Symfony\Component\Console\Command\Command". - */ public function testProcessThrowAnExceptionIfTheServiceIsNotASubclassOfCommand() { + $this->expectException('InvalidArgumentException'); + $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); @@ -223,12 +222,10 @@ class AddConsoleCommandPassTest extends TestCase $this->assertInstanceOf($className, $command); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage The definition for "my-child-command" has no class. - */ public function testProcessOnChildDefinitionWithoutClass() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('The definition for "my-child-command" has no class.'); $container = new ContainerBuilder(); $container->addCompilerPass(new AddConsoleCommandPass(), PassConfig::TYPE_BEFORE_REMOVING); diff --git a/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterStyleStackTest.php b/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterStyleStackTest.php index e212bf25ec..b170d8d00b 100644 --- a/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterStyleStackTest.php +++ b/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterStyleStackTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Console\Tests\Formatter; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Symfony\Component\Console\Formatter\OutputFormatterStyleStack; class OutputFormatterStyleStackTest extends TestCase { + use ForwardCompatTestTrait; + public function testPush() { $stack = new OutputFormatterStyleStack(); @@ -59,11 +62,9 @@ class OutputFormatterStyleStackTest extends TestCase $this->assertEquals($s1, $stack->pop()); } - /** - * @expectedException \InvalidArgumentException - */ public function testInvalidPop() { + $this->expectException('InvalidArgumentException'); $stack = new OutputFormatterStyleStack(); $stack->push(new OutputFormatterStyle('white', 'black')); $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 6c6f86f36e..df3a840927 100644 --- a/src/Symfony/Component/Console/Tests/Helper/ProgressIndicatorTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/ProgressIndicatorTest.php @@ -3,6 +3,7 @@ namespace Symfony\Component\Console\Tests\Helper; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Console\Helper\ProgressIndicator; use Symfony\Component\Console\Output\StreamOutput; @@ -11,6 +12,8 @@ use Symfony\Component\Console\Output\StreamOutput; */ class ProgressIndicatorTest extends TestCase { + use ForwardCompatTestTrait; + public function testDefaultIndicator() { $bar = new ProgressIndicator($output = $this->getOutputStream()); @@ -100,42 +103,34 @@ class ProgressIndicatorTest extends TestCase ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Must have at least 2 indicator value characters. - */ public function testCannotSetInvalidIndicatorCharacters() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Must have at least 2 indicator value characters.'); $bar = new ProgressIndicator($this->getOutputStream(), null, 100, ['1']); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Progress indicator already started. - */ public function testCannotStartAlreadyStartedIndicator() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Progress indicator already started.'); $bar = new ProgressIndicator($this->getOutputStream()); $bar->start('Starting...'); $bar->start('Starting Again.'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Progress indicator has not yet been started. - */ public function testCannotAdvanceUnstartedIndicator() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Progress indicator has not yet been started.'); $bar = new ProgressIndicator($this->getOutputStream()); $bar->advance(); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Progress indicator has not yet been started. - */ public function testCannotFinishUnstartedIndicator() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Progress indicator has not yet been started.'); $bar = new ProgressIndicator($this->getOutputStream()); $bar->finish('Finished'); } diff --git a/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php b/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php index 19e9f355d4..990556c540 100644 --- a/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Console\Tests\Helper; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Helper\FormatterHelper; use Symfony\Component\Console\Helper\HelperSet; @@ -25,6 +26,8 @@ use Symfony\Component\Console\Question\Question; */ class QuestionHelperTest extends AbstractQuestionHelperTest { + use ForwardCompatTestTrait; + public function testAskChoice() { $questionHelper = new QuestionHelper(); @@ -624,12 +627,10 @@ class QuestionHelperTest extends AbstractQuestionHelperTest $this->assertSame($expectedValue, $answer); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The provided answer is ambiguous. Value should be one of env_2 or env_3. - */ public function testAmbiguousChoiceFromChoicelist() { + $this->expectException('InvalidArgumentException'); + $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', @@ -693,32 +694,26 @@ class QuestionHelperTest extends AbstractQuestionHelperTest $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("\n")), $output, $question); } - /** - * @expectedException \Symfony\Component\Console\Exception\RuntimeException - * @expectedExceptionMessage Aborted. - */ public function testAskThrowsExceptionOnMissingInput() { + $this->expectException('Symfony\Component\Console\Exception\RuntimeException'); + $this->expectExceptionMessage('Aborted.'); $dialog = new QuestionHelper(); $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new Question('What\'s your name?')); } - /** - * @expectedException \Symfony\Component\Console\Exception\RuntimeException - * @expectedExceptionMessage Aborted. - */ public function testAskThrowsExceptionOnMissingInputForChoiceQuestion() { + $this->expectException('Symfony\Component\Console\Exception\RuntimeException'); + $this->expectExceptionMessage('Aborted.'); $dialog = new QuestionHelper(); $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new ChoiceQuestion('Choice', ['a', 'b'])); } - /** - * @expectedException \Symfony\Component\Console\Exception\RuntimeException - * @expectedExceptionMessage Aborted. - */ public function testAskThrowsExceptionOnMissingInputWithValidator() { + $this->expectException('Symfony\Component\Console\Exception\RuntimeException'); + $this->expectExceptionMessage('Aborted.'); $dialog = new QuestionHelper(); $question = new Question('What\'s your name?'); @@ -731,12 +726,10 @@ class QuestionHelperTest extends AbstractQuestionHelperTest $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), $question); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Choice question must have at least 1 choice available. - */ public function testEmptyChoices() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Choice question must have at least 1 choice available.'); new ChoiceQuestion('Question', [], 'irrelevant'); } diff --git a/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php b/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php index 6f621db954..e464303782 100644 --- a/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php @@ -2,6 +2,7 @@ namespace Symfony\Component\Console\Tests\Helper; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Console\Helper\FormatterHelper; use Symfony\Component\Console\Helper\HelperSet; use Symfony\Component\Console\Helper\SymfonyQuestionHelper; @@ -14,6 +15,8 @@ use Symfony\Component\Console\Question\Question; */ class SymfonyQuestionHelperTest extends AbstractQuestionHelperTest { + use ForwardCompatTestTrait; + public function testAskChoice() { $questionHelper = new SymfonyQuestionHelper(); @@ -122,12 +125,10 @@ class SymfonyQuestionHelperTest extends AbstractQuestionHelperTest $this->assertOutputContains('Question with a trailing \\', $output); } - /** - * @expectedException \Symfony\Component\Console\Exception\RuntimeException - * @expectedExceptionMessage Aborted. - */ public function testAskThrowsExceptionOnMissingInput() { + $this->expectException('Symfony\Component\Console\Exception\RuntimeException'); + $this->expectExceptionMessage('Aborted.'); $dialog = new SymfonyQuestionHelper(); $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new Question('What\'s your name?')); } diff --git a/src/Symfony/Component/Console/Tests/Helper/TableStyleTest.php b/src/Symfony/Component/Console/Tests/Helper/TableStyleTest.php index 58b16170a4..7ec1f98cb6 100644 --- a/src/Symfony/Component/Console/Tests/Helper/TableStyleTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/TableStyleTest.php @@ -12,16 +12,17 @@ namespace Symfony\Component\Console\Tests\Helper; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Console\Helper\TableStyle; class TableStyleTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid padding type. Expected one of (STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH). - */ + use ForwardCompatTestTrait; + public function testSetPadTypeWithInvalidType() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Invalid padding type. Expected one of (STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH).'); $style = new TableStyle(); $style->setPadType(31); } diff --git a/src/Symfony/Component/Console/Tests/Helper/TableTest.php b/src/Symfony/Component/Console/Tests/Helper/TableTest.php index a320933d8b..7862df2c00 100644 --- a/src/Symfony/Component/Console/Tests/Helper/TableTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/TableTest.php @@ -770,12 +770,10 @@ TABLE; $this->assertEquals($expected, $this->getOutputContent($output)); } - /** - * @expectedException \Symfony\Component\Console\Exception\InvalidArgumentException - * @expectedExceptionMessage A cell must be a TableCell, a scalar or an object implementing __toString, array given. - */ public function testThrowsWhenTheCellInAnArray() { + $this->expectException('Symfony\Component\Console\Exception\InvalidArgumentException'); + $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']) @@ -947,33 +945,27 @@ TABLE; $this->assertEquals($expected, $this->getOutputContent($output)); } - /** - * @expectedException \Symfony\Component\Console\Exception\RuntimeException - * @expectedExceptionMessage Output should be an instance of "Symfony\Component\Console\Output\ConsoleSectionOutput" when calling "Symfony\Component\Console\Helper\Table::appendRow". - */ public function testAppendRowWithoutSectionOutput() { + $this->expectException('Symfony\Component\Console\Exception\RuntimeException'); + $this->expectExceptionMessage('Output should be an instance of "Symfony\Component\Console\Output\ConsoleSectionOutput" when calling "Symfony\Component\Console\Helper\Table::appendRow".'); $table = new Table($this->getOutputStream()); $table->appendRow(['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25']); } - /** - * @expectedException \Symfony\Component\Console\Exception\InvalidArgumentException - * @expectedExceptionMessage Style "absent" is not defined. - */ public function testIsNotDefinedStyleException() { + $this->expectException('Symfony\Component\Console\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Style "absent" is not defined.'); $table = new Table($this->getOutputStream()); $table->setStyle('absent'); } - /** - * @expectedException \Symfony\Component\Console\Exception\InvalidArgumentException - * @expectedExceptionMessage Style "absent" is not defined. - */ public function testGetStyleDefinition() { + $this->expectException('Symfony\Component\Console\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Style "absent" is not defined.'); Table::getStyleDefinition('absent'); } diff --git a/src/Symfony/Component/Console/Tests/Input/InputArgumentTest.php b/src/Symfony/Component/Console/Tests/Input/InputArgumentTest.php index 18cead1524..c8e6336c03 100644 --- a/src/Symfony/Component/Console/Tests/Input/InputArgumentTest.php +++ b/src/Symfony/Component/Console/Tests/Input/InputArgumentTest.php @@ -83,22 +83,18 @@ class InputArgumentTest extends TestCase $this->assertEquals([1, 2], $argument->getDefault(), '->setDefault() changes the default value'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Cannot set a default value except for InputArgument::OPTIONAL mode. - */ public function testSetDefaultWithRequiredArgument() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Cannot set a default value except for InputArgument::OPTIONAL mode.'); $argument = new InputArgument('foo', InputArgument::REQUIRED); $argument->setDefault('default'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage A default value for an array argument must be an array. - */ public function testSetDefaultWithArrayArgument() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('A default value for an array argument must be an array.'); $argument = new InputArgument('foo', InputArgument::IS_ARRAY); $argument->setDefault('default'); } diff --git a/src/Symfony/Component/Console/Tests/Input/InputDefinitionTest.php b/src/Symfony/Component/Console/Tests/Input/InputDefinitionTest.php index c5c7ab0ff0..7deb638335 100644 --- a/src/Symfony/Component/Console/Tests/Input/InputDefinitionTest.php +++ b/src/Symfony/Component/Console/Tests/Input/InputDefinitionTest.php @@ -89,12 +89,10 @@ class InputDefinitionTest extends TestCase $this->assertEquals(['foo' => $this->foo, 'bar' => $this->bar], $definition->getArguments(), '->addArgument() adds a InputArgument object'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage An argument with name "foo" already exists. - */ public function testArgumentsMustHaveDifferentNames() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('An argument with name "foo" already exists.'); $this->initializeArguments(); $definition = new InputDefinition(); @@ -102,12 +100,10 @@ class InputDefinitionTest extends TestCase $definition->addArgument($this->foo1); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Cannot add an argument after an array argument. - */ public function testArrayArgumentHasToBeLast() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Cannot add an argument after an array argument.'); $this->initializeArguments(); $definition = new InputDefinition(); @@ -115,12 +111,10 @@ class InputDefinitionTest extends TestCase $definition->addArgument(new InputArgument('anotherbar')); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Cannot add a required argument after an optional one. - */ public function testRequiredArgumentCannotFollowAnOptionalOne() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Cannot add a required argument after an optional one.'); $this->initializeArguments(); $definition = new InputDefinition(); @@ -137,12 +131,10 @@ class InputDefinitionTest extends TestCase $this->assertEquals($this->foo, $definition->getArgument('foo'), '->getArgument() returns a InputArgument by its name'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "bar" argument does not exist. - */ public function testGetInvalidArgument() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "bar" argument does not exist.'); $this->initializeArguments(); $definition = new InputDefinition(); @@ -209,12 +201,10 @@ class InputDefinitionTest extends TestCase $this->assertEquals(['bar' => $this->bar], $definition->getOptions(), '->setOptions() clears all InputOption objects'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "-f" option does not exist. - */ public function testSetOptionsClearsOptions() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "-f" option does not exist.'); $this->initializeOptions(); $definition = new InputDefinition([$this->foo]); @@ -243,12 +233,10 @@ class InputDefinitionTest extends TestCase $this->assertEquals(['foo' => $this->foo, 'bar' => $this->bar], $definition->getOptions(), '->addOption() adds a InputOption object'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage An option named "foo" already exists. - */ public function testAddDuplicateOption() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('An option named "foo" already exists.'); $this->initializeOptions(); $definition = new InputDefinition(); @@ -256,12 +244,10 @@ class InputDefinitionTest extends TestCase $definition->addOption($this->foo2); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage An option with shortcut "f" already exists. - */ public function testAddDuplicateShortcutOption() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('An option with shortcut "f" already exists.'); $this->initializeOptions(); $definition = new InputDefinition(); @@ -277,12 +263,10 @@ class InputDefinitionTest extends TestCase $this->assertEquals($this->foo, $definition->getOption('foo'), '->getOption() returns a InputOption by its name'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "--bar" option does not exist. - */ public function testGetInvalidOption() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "--bar" option does not exist.'); $this->initializeOptions(); $definition = new InputDefinition([$this->foo]); @@ -324,12 +308,10 @@ class InputDefinitionTest extends TestCase $this->assertEquals($this->multi, $definition->getOptionForShortcut('mmm'), '->getOptionForShortcut() returns a InputOption by its shortcut'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "-l" option does not exist. - */ public function testGetOptionForInvalidShortcut() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "-l" option does not exist.'); $this->initializeOptions(); $definition = new InputDefinition([$this->foo]); diff --git a/src/Symfony/Component/Console/Tests/Input/InputOptionTest.php b/src/Symfony/Component/Console/Tests/Input/InputOptionTest.php index 45fcd681a8..982dbadfdc 100644 --- a/src/Symfony/Component/Console/Tests/Input/InputOptionTest.php +++ b/src/Symfony/Component/Console/Tests/Input/InputOptionTest.php @@ -27,12 +27,10 @@ class InputOptionTest extends TestCase $this->assertEquals('foo', $option->getName(), '__construct() removes the leading -- of the option name'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value. - */ public function testArrayModeWithoutValue() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value.'); new InputOption('foo', 'f', InputOption::VALUE_IS_ARRAY); } @@ -84,27 +82,21 @@ class InputOptionTest extends TestCase new InputOption('foo', 'f', '-1'); } - /** - * @expectedException \InvalidArgumentException - */ public function testEmptyNameIsInvalid() { + $this->expectException('InvalidArgumentException'); new InputOption(''); } - /** - * @expectedException \InvalidArgumentException - */ public function testDoubleDashNameIsInvalid() { + $this->expectException('InvalidArgumentException'); new InputOption('--'); } - /** - * @expectedException \InvalidArgumentException - */ public function testSingleDashOptionIsInvalid() { + $this->expectException('InvalidArgumentException'); new InputOption('foo', '-'); } @@ -153,22 +145,18 @@ class InputOptionTest extends TestCase $this->assertEquals([1, 2], $option->getDefault(), '->setDefault() changes the default value'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Cannot set a default value when using InputOption::VALUE_NONE mode. - */ public function testDefaultValueWithValueNoneMode() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Cannot set a default value when using InputOption::VALUE_NONE mode.'); $option = new InputOption('foo', 'f', InputOption::VALUE_NONE); $option->setDefault('default'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage A default value for an array option must be an array. - */ public function testDefaultValueWithIsArrayMode() { + $this->expectException('LogicException'); + $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'); } diff --git a/src/Symfony/Component/Console/Tests/Input/InputTest.php b/src/Symfony/Component/Console/Tests/Input/InputTest.php index 61608bf27c..a387b0a420 100644 --- a/src/Symfony/Component/Console/Tests/Input/InputTest.php +++ b/src/Symfony/Component/Console/Tests/Input/InputTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Console\Tests\Input; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputDefinition; @@ -19,6 +20,8 @@ use Symfony\Component\Console\Input\InputOption; class InputTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $input = new ArrayInput(['name' => 'foo'], new InputDefinition([new InputArgument('name')])); @@ -47,22 +50,18 @@ class InputTest extends TestCase $this->assertEquals(['name' => 'foo', 'bar' => null], $input->getOptions(), '->getOptions() returns all option values'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "foo" option does not exist. - */ public function testSetInvalidOption() { + $this->expectException('InvalidArgumentException'); + $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'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "foo" option does not exist. - */ public function testGetInvalidOption() { + $this->expectException('InvalidArgumentException'); + $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'); } @@ -81,43 +80,35 @@ class InputTest extends TestCase $this->assertEquals(['name' => 'foo', 'bar' => 'default'], $input->getArguments(), '->getArguments() returns all argument values, even optional ones'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "foo" argument does not exist. - */ public function testSetInvalidArgument() { + $this->expectException('InvalidArgumentException'); + $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'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "foo" argument does not exist. - */ public function testGetInvalidArgument() { + $this->expectException('InvalidArgumentException'); + $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'); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Not enough arguments (missing: "name"). - */ public function testValidateWithMissingArguments() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Not enough arguments (missing: "name").'); $input = new ArrayInput([]); $input->bind(new InputDefinition([new InputArgument('name', InputArgument::REQUIRED)])); $input->validate(); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Not enough arguments (missing: "name"). - */ public function testValidateWithMissingRequiredArguments() { + $this->expectException('RuntimeException'); + $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)])); $input->validate(); diff --git a/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php b/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php index c99eb839b7..591f58a62f 100644 --- a/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php +++ b/src/Symfony/Component/Console/Tests/Logger/ConsoleLoggerTest.php @@ -14,6 +14,7 @@ namespace Symfony\Component\Console\Tests\Logger; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Console\Logger\ConsoleLogger; use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Output\OutputInterface; @@ -27,6 +28,8 @@ use Symfony\Component\Console\Tests\Fixtures\DummyOutput; */ class ConsoleLoggerTest extends TestCase { + use ForwardCompatTestTrait; + /** * @var DummyOutput */ @@ -141,11 +144,9 @@ class ConsoleLoggerTest extends TestCase ]; } - /** - * @expectedException \Psr\Log\InvalidArgumentException - */ public function testThrowsOnInvalidLevel() { + $this->expectException('Psr\Log\InvalidArgumentException'); $logger = $this->getLogger(); $logger->log('invalid level', 'Foo'); } diff --git a/src/Symfony/Component/Console/Tests/Output/StreamOutputTest.php b/src/Symfony/Component/Console/Tests/Output/StreamOutputTest.php index 78a094ccdb..b9c08db494 100644 --- a/src/Symfony/Component/Console/Tests/Output/StreamOutputTest.php +++ b/src/Symfony/Component/Console/Tests/Output/StreamOutputTest.php @@ -39,12 +39,10 @@ class StreamOutputTest extends TestCase $this->assertTrue($output->isDecorated(), '__construct() takes the decorated flag as its second argument'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The StreamOutput class needs a stream as its first argument. - */ public function testStreamIsRequired() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The StreamOutput class needs a stream as its first argument.'); new StreamOutput('foo'); } diff --git a/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php b/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php index 7db663222a..7b3d564df9 100644 --- a/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php +++ b/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php @@ -141,12 +141,10 @@ class CommandTesterTest extends TestCase $this->assertEquals(implode('', $questions), $tester->getDisplay(true)); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Aborted. - */ public function testCommandWithWrongInputsNumber() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Aborted.'); $questions = [ 'What\'s your name?', 'How are you?', @@ -168,12 +166,10 @@ class CommandTesterTest extends TestCase $tester->execute([]); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Aborted. - */ public function testCommandWithQuestionsButNoInputs() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Aborted.'); $questions = [ 'What\'s your name?', 'How are you?', diff --git a/src/Symfony/Component/CssSelector/Tests/CssSelectorConverterTest.php b/src/Symfony/Component/CssSelector/Tests/CssSelectorConverterTest.php index cd0fd785e5..8c96a80e59 100644 --- a/src/Symfony/Component/CssSelector/Tests/CssSelectorConverterTest.php +++ b/src/Symfony/Component/CssSelector/Tests/CssSelectorConverterTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\CssSelector\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\CssSelector\CssSelectorConverter; class CssSelectorConverterTest extends TestCase { + use ForwardCompatTestTrait; + public function testCssToXPath() { $converter = new CssSelectorConverter(); @@ -35,12 +38,10 @@ class CssSelectorConverterTest extends TestCase $this->assertEquals('descendant-or-self::H1', $converter->toXPath('H1')); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ParseException - * @expectedExceptionMessage Expected identifier, but found. - */ public function testParseExceptions() { + $this->expectException('Symfony\Component\CssSelector\Exception\ParseException'); + $this->expectExceptionMessage('Expected identifier, but found.'); $converter = new CssSelectorConverter(); $converter->toXPath('h1:'); } diff --git a/src/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.php b/src/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.php index a9ab29e2ad..cd821635ac 100644 --- a/src/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.php +++ b/src/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\CssSelector\Tests\XPath; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\CssSelector\Node\ElementNode; use Symfony\Component\CssSelector\Node\FunctionNode; use Symfony\Component\CssSelector\Parser\Parser; @@ -21,6 +22,8 @@ use Symfony\Component\CssSelector\XPath\XPathExpr; class TranslatorTest extends TestCase { + use ForwardCompatTestTrait; + /** @dataProvider getXpathLiteralTestData */ public function testXpathLiteral($value, $literal) { @@ -35,31 +38,25 @@ class TranslatorTest extends TestCase $this->assertEquals($xpath, $translator->cssToXPath($css, '')); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ExpressionErrorException - */ public function testCssToXPathPseudoElement() { + $this->expectException('Symfony\Component\CssSelector\Exception\ExpressionErrorException'); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $translator->cssToXPath('e::first-line'); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ExpressionErrorException - */ public function testGetExtensionNotExistsExtension() { + $this->expectException('Symfony\Component\CssSelector\Exception\ExpressionErrorException'); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $translator->getExtension('fake'); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ExpressionErrorException - */ public function testAddCombinationNotExistsExtension() { + $this->expectException('Symfony\Component\CssSelector\Exception\ExpressionErrorException'); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $parser = new Parser(); @@ -68,11 +65,9 @@ class TranslatorTest extends TestCase $translator->addCombination('fake', $xpath, $combinedXpath); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ExpressionErrorException - */ public function testAddFunctionNotExistsFunction() { + $this->expectException('Symfony\Component\CssSelector\Exception\ExpressionErrorException'); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $xpath = new XPathExpr(); @@ -80,22 +75,18 @@ class TranslatorTest extends TestCase $translator->addFunction($xpath, $function); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ExpressionErrorException - */ public function testAddPseudoClassNotExistsClass() { + $this->expectException('Symfony\Component\CssSelector\Exception\ExpressionErrorException'); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $xpath = new XPathExpr(); $translator->addPseudoClass($xpath, 'fake'); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ExpressionErrorException - */ public function testAddAttributeMatchingClassNotExistsClass() { + $this->expectException('Symfony\Component\CssSelector\Exception\ExpressionErrorException'); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $xpath = new XPathExpr(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/AliasTest.php b/src/Symfony/Component/DependencyInjection/Tests/AliasTest.php index f382450afc..7f35edc065 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/AliasTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/AliasTest.php @@ -87,10 +87,10 @@ class AliasTest extends TestCase /** * @dataProvider invalidDeprecationMessageProvider - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException */ public function testCannotDeprecateWithAnInvalidTemplate($message) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $def = new Alias('foo'); $def->setDeprecated(true, $message); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php b/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php index b1eef8d24b..7a60043070 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\DependencyInjection\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\ChildDefinition; class ChildDefinitionTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $def = new ChildDefinition('foo'); @@ -89,11 +92,9 @@ class ChildDefinitionTest extends TestCase $this->assertSame(['index_0' => 'foo'], $def->getArguments()); } - /** - * @expectedException \InvalidArgumentException - */ public function testReplaceArgumentShouldRequireIntegerIndex() { + $this->expectException('InvalidArgumentException'); $def = new ChildDefinition('foo'); $def->replaceArgument('0', 'foo'); @@ -118,11 +119,9 @@ class ChildDefinitionTest extends TestCase $this->assertSame([0 => 'foo', 1 => 'bar', 'index_1' => 'baz', '$bar' => 'val'], $def->getArguments()); } - /** - * @expectedException \OutOfBoundsException - */ public function testGetArgumentShouldCheckBounds() { + $this->expectException('OutOfBoundsException'); $def = new ChildDefinition('foo'); $def->setArguments([0 => 'foo']); @@ -131,20 +130,16 @@ class ChildDefinitionTest extends TestCase $def->getArgument(1); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\BadMethodCallException - */ public function testCannotCallSetAutoconfigured() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\BadMethodCallException'); $def = new ChildDefinition('foo'); $def->setAutoconfigured(true); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\BadMethodCallException - */ public function testCannotCallSetInstanceofConditionals() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\BadMethodCallException'); $def = new ChildDefinition('foo'); $def->setInstanceofConditionals(['Foo' => new ChildDefinition('')]); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php index d029636a7c..159342f6fd 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php @@ -12,16 +12,17 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Compiler\AutoAliasServicePass; use Symfony\Component\DependencyInjection\ContainerBuilder; class AutoAliasServicePassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException - */ + use ForwardCompatTestTrait; + public function testProcessWithMissingParameter() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException'); $container = new ContainerBuilder(); $container->register('example') @@ -31,11 +32,9 @@ class AutoAliasServicePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - */ public function testProcessWithMissingFormat() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $container = new ContainerBuilder(); $container->register('example') diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php index 10c386f13c..b040147b6b 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php @@ -54,12 +54,10 @@ class AutowirePassTest extends TestCase $this->assertEquals(Foo::class, (string) $container->getDefinition('bar')->getArgument(0)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "Symfony\Component\DependencyInjection\Tests\CompilerEslaAction": argument "$notExisting" of method "Symfony\Component\DependencyInjection\Tests\Compiler\ElsaAction::__construct()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\NotExisting" but this class was not found. - */ public function testProcessNotExistingActionParam() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "Symfony\Component\DependencyInjection\Tests\CompilerEslaAction": argument "$notExisting" of method "Symfony\Component\DependencyInjection\Tests\Compiler\ElsaAction::__construct()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\NotExisting" but this class was not found.'); $container = new ContainerBuilder(); $container->register(Foo::class); @@ -84,12 +82,10 @@ class AutowirePassTest extends TestCase $this->assertEquals(Foo::class, (string) $container->getDefinition('fooVariadic')->getArgument(0)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Cannot autowire service "c": argument "$a" of method "Symfony\Component\DependencyInjection\Tests\Compiler\C::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\A" but no such service exists. You should maybe alias this class to the existing "Symfony\Component\DependencyInjection\Tests\Compiler\B" service. - */ public function testProcessAutowireParent() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Cannot autowire service "c": argument "$a" of method "Symfony\Component\DependencyInjection\Tests\Compiler\C::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\A" but no such service exists. You should maybe alias this class to the existing "Symfony\Component\DependencyInjection\Tests\Compiler\B" service.'); $container = new ContainerBuilder(); $container->register(B::class); @@ -103,12 +99,10 @@ class AutowirePassTest extends TestCase $this->assertEquals(B::class, (string) $container->getDefinition('c')->getArgument(0)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Cannot autowire service "g": argument "$d" of method "Symfony\Component\DependencyInjection\Tests\Compiler\G::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\DInterface" but no such service exists. You should maybe alias this interface to the existing "Symfony\Component\DependencyInjection\Tests\Compiler\F" service. - */ public function testProcessAutowireInterface() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Cannot autowire service "g": argument "$d" of method "Symfony\Component\DependencyInjection\Tests\Compiler\G::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\DInterface" but no such service exists. You should maybe alias this interface to the existing "Symfony\Component\DependencyInjection\Tests\Compiler\F" service.'); $container = new ContainerBuilder(); $container->register(F::class); @@ -158,12 +152,10 @@ class AutowirePassTest extends TestCase $this->assertEquals(DInterface::class, (string) $container->getDefinition('h')->getArgument(1)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Invalid service "private_service": constructor of class "Symfony\Component\DependencyInjection\Tests\Compiler\PrivateConstructor" must be public. - */ public function testPrivateConstructorThrowsAutowireException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Invalid service "private_service": constructor of class "Symfony\Component\DependencyInjection\Tests\Compiler\PrivateConstructor" must be public.'); $container = new ContainerBuilder(); $container->autowire('private_service', __NAMESPACE__.'\PrivateConstructor'); @@ -172,12 +164,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "a": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\CannotBeAutowired::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but no such service exists. You should maybe alias this interface to one of these existing services: "c1", "c2", "c3". - */ public function testTypeCollision() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "a": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\CannotBeAutowired::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but no such service exists. You should maybe alias this interface to one of these existing services: "c1", "c2", "c3".'); $container = new ContainerBuilder(); $container->register('c1', __NAMESPACE__.'\CollisionA'); @@ -190,12 +180,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "a": argument "$k" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotGuessableArgument::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\Foo" but no such service exists. You should maybe alias this class to one of these existing services: "a1", "a2". - */ public function testTypeNotGuessable() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "a": argument "$k" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotGuessableArgument::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\Foo" but no such service exists. You should maybe alias this class to one of these existing services: "a1", "a2".'); $container = new ContainerBuilder(); $container->register('a1', __NAMESPACE__.'\Foo'); @@ -207,12 +195,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "a": argument "$k" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotGuessableArgumentForSubclass::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\A" but no such service exists. You should maybe alias this class to one of these existing services: "a1", "a2". - */ public function testTypeNotGuessableWithSubclass() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "a": argument "$k" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotGuessableArgumentForSubclass::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\A" but no such service exists. You should maybe alias this class to one of these existing services: "a1", "a2".'); $container = new ContainerBuilder(); $container->register('a1', __NAMESPACE__.'\B'); @@ -224,12 +210,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "a": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\CannotBeAutowired::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but no such service exists. - */ public function testTypeNotGuessableNoServicesFound() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "a": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\CannotBeAutowired::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but no such service exists.'); $container = new ContainerBuilder(); $aDefinition = $container->register('a', __NAMESPACE__.'\CannotBeAutowired'); @@ -273,12 +257,10 @@ class AutowirePassTest extends TestCase $this->assertEquals(CollisionInterface::class, (string) $container->getDefinition('a')->getArgument(0)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "coop_tilleuls": argument "$j" of method "Symfony\Component\DependencyInjection\Tests\Compiler\LesTilleuls::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\Dunglas" but no such service exists. - */ public function testServicesAreNotAutoCreated() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "coop_tilleuls": argument "$j" of method "Symfony\Component\DependencyInjection\Tests\Compiler\LesTilleuls::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\Dunglas" but no such service exists.'); $container = new ContainerBuilder(); $coopTilleulsDefinition = $container->register('coop_tilleuls', __NAMESPACE__.'\LesTilleuls'); @@ -334,12 +316,10 @@ class AutowirePassTest extends TestCase $this->assertCount(0, $container->getDefinition('bar')->getArguments()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "a": argument "$r" of method "Symfony\Component\DependencyInjection\Tests\Compiler\BadTypeHintedArgument::__construct()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\NotARealClass" but this class was not found. - */ public function testClassNotFoundThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "a": argument "$r" of method "Symfony\Component\DependencyInjection\Tests\Compiler\BadTypeHintedArgument::__construct()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\NotARealClass" but this class was not found.'); $container = new ContainerBuilder(); $aDefinition = $container->register('a', __NAMESPACE__.'\BadTypeHintedArgument'); @@ -351,12 +331,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "a": argument "$r" of method "Symfony\Component\DependencyInjection\Tests\Compiler\BadParentTypeHintedArgument::__construct()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\OptionalServiceClass" but this class is missing a parent class (Class Symfony\Bug\NotExistClass not found). - */ public function testParentClassNotFoundThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "a": argument "$r" of method "Symfony\Component\DependencyInjection\Tests\Compiler\BadParentTypeHintedArgument::__construct()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\OptionalServiceClass" but this class is missing a parent class (Class Symfony\Bug\NotExistClass not found).'); if (\PHP_VERSION_ID >= 70400) { throw new Warning('PHP 7.4 breaks this test, see https://bugs.php.net/78351.'); } @@ -372,12 +350,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "bar": argument "$foo" of method "Symfony\Component\DependencyInjection\Tests\Compiler\Bar::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\Foo" but this service is abstract. You should maybe alias this class to the existing "foo" service. - */ public function testDontUseAbstractServices() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "bar": argument "$foo" of method "Symfony\Component\DependencyInjection\Tests\Compiler\Bar::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\Foo" but this service is abstract. You should maybe alias this class to the existing "foo" service.'); $container = new ContainerBuilder(); $container->register(Foo::class)->setAbstract(true); @@ -419,12 +395,10 @@ class AutowirePassTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "arg_no_type_hint": argument "$bar" of method "Symfony\Component\DependencyInjection\Tests\Compiler\MultipleArguments::__construct()" is type-hinted "array", you should configure its value explicitly. - */ public function testScalarArgsCannotBeAutowired() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "arg_no_type_hint": argument "$bar" of method "Symfony\Component\DependencyInjection\Tests\Compiler\MultipleArguments::__construct()" is type-hinted "array", you should configure its value explicitly.'); $container = new ContainerBuilder(); $container->register(A::class); @@ -437,12 +411,10 @@ class AutowirePassTest extends TestCase (new AutowirePass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "arg_no_type_hint": argument "$foo" of method "Symfony\Component\DependencyInjection\Tests\Compiler\MultipleArguments::__construct()" has no type-hint, you should configure its value explicitly. - */ public function testNoTypeArgsCannotBeAutowired() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "arg_no_type_hint": argument "$foo" of method "Symfony\Component\DependencyInjection\Tests\Compiler\MultipleArguments::__construct()" has no type-hint, you should configure its value explicitly.'); $container = new ContainerBuilder(); $container->register(A::class); @@ -571,11 +543,11 @@ class AutowirePassTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException * @exceptedExceptionMessage Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "setLogger()" does not exist. */ public function testWithNonExistingSetterAndAutowiring() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $definition = $container->register(CaseSensitiveClass::class, CaseSensitiveClass::class)->setAutowired(true); @@ -667,12 +639,10 @@ class AutowirePassTest extends TestCase $this->assertSame('Cannot autowire service "setter_injection_collision": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\SetterInjectionCollision::setMultipleInstancesForOneArg()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but no such service exists. You should maybe alias this interface to one of these existing services: "c1", "c2".', (string) $e->getMessage()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "my_service": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\K::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" but no such service exists. Did you create a class that implements this interface? - */ public function testInterfaceWithNoImplementationSuggestToWriteOne() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "my_service": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\K::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" but no such service exists. Did you create a class that implements this interface?'); $container = new ContainerBuilder(); $aDefinition = $container->register('my_service', K::class); @@ -684,12 +654,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "bar": argument "$foo" of method "Symfony\Component\DependencyInjection\Tests\Compiler\Bar::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\Foo" but no such service exists. You should maybe alias this class to the existing "foo" service. - */ public function testProcessDoesNotTriggerDeprecations() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "bar": argument "$foo" of method "Symfony\Component\DependencyInjection\Tests\Compiler\Bar::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\Foo" but no such service exists. You should maybe alias this class to the existing "foo" service.'); $container = new ContainerBuilder(); $container->register('deprecated', 'Symfony\Component\DependencyInjection\Tests\Fixtures\DeprecatedClass')->setDeprecated(true); $container->register('foo', __NAMESPACE__.'\Foo'); @@ -736,10 +704,10 @@ class AutowirePassTest extends TestCase /** * @dataProvider provideNotWireableCalls - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException */ public function testNotWireableCalls($method, $expectedMsg) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); $container = new ContainerBuilder(); $foo = $container->register('foo', NotWireable::class)->setAutowired(true) @@ -770,12 +738,10 @@ class AutowirePassTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "foo": argument "$sam" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotWireable::setNotAutowireableBecauseOfATypo()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\lesTilleuls" but no such service exists. Did you mean "Symfony\Component\DependencyInjection\Tests\Compiler\LesTilleuls"? - */ public function testSuggestRegisteredServicesWithSimilarCase() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "foo": argument "$sam" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotWireable::setNotAutowireableBecauseOfATypo()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\lesTilleuls" but no such service exists. Did you mean "Symfony\Component\DependencyInjection\Tests\Compiler\LesTilleuls"?'); $container = new ContainerBuilder(); $container->register(LesTilleuls::class, LesTilleuls::class); @@ -788,12 +754,10 @@ class AutowirePassTest extends TestCase (new AutowirePass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. Try changing the type-hint to "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" instead. - */ public function testByIdAlternative() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. Try changing the type-hint to "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" instead.'); $container = new ContainerBuilder(); $container->setAlias(IInterface::class, 'i'); @@ -805,12 +769,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. Try changing the type-hint to "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" instead. - */ public function testExceptionWhenAliasExists() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. Try changing the type-hint to "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" instead.'); $container = new ContainerBuilder(); // multiple I services... but there *is* IInterface available @@ -825,12 +787,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. You should maybe alias this class to one of these existing services: "i", "i2". - */ public function testExceptionWhenAliasDoesNotExist() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. You should maybe alias this class to one of these existing services: "i", "i2".'); if (\PHP_VERSION_ID >= 70400) { throw new Warning('PHP 7.4 breaks this test, see https://bugs.php.net/78351.'); } @@ -919,12 +879,10 @@ class AutowirePassTest extends TestCase $this->assertSame('renamed', (string) $definition->getArgument(1)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "Symfony\Component\DependencyInjection\Tests\Compiler\NonAutowirableDecorator": argument "$decorated1" of method "__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\DecoratorInterface" but no such service exists. You should maybe alias this interface to one of these existing services: "Symfony\Component\DependencyInjection\Tests\Compiler\NonAutowirableDecorator", "Symfony\Component\DependencyInjection\Tests\Compiler\NonAutowirableDecorator.inner". - */ public function testDoNotAutowireDecoratorWhenSeveralArgumentOfTheType() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "Symfony\Component\DependencyInjection\Tests\Compiler\NonAutowirableDecorator": argument "$decorated1" of method "__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\DecoratorInterface" but no such service exists. You should maybe alias this interface to one of these existing services: "Symfony\Component\DependencyInjection\Tests\Compiler\NonAutowirableDecorator", "Symfony\Component\DependencyInjection\Tests\Compiler\NonAutowirableDecorator.inner".'); $container = new ContainerBuilder(); $container->register(LoggerInterface::class, NullLogger::class); $container->register(Decorated::class, Decorated::class); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckArgumentsValidityPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckArgumentsValidityPassTest.php index c1e47b308e..a1a700337c 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckArgumentsValidityPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckArgumentsValidityPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Compiler\CheckArgumentsValidityPass; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -20,6 +21,8 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; */ class CheckArgumentsValidityPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testProcess() { $container = new ContainerBuilder(); @@ -41,11 +44,11 @@ class CheckArgumentsValidityPassTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException * @dataProvider definitionProvider */ public function testException(array $arguments, array $methodCalls) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $definition = $container->register('foo'); $definition->setArguments($arguments); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.php index a0a2412535..51bb809733 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; use Symfony\Component\DependencyInjection\Compiler\CheckCircularReferencesPass; @@ -21,11 +22,11 @@ use Symfony\Component\DependencyInjection\Reference; class CheckCircularReferencesPassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ + use ForwardCompatTestTrait; + public function testProcess() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('a')); @@ -33,11 +34,9 @@ class CheckCircularReferencesPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testProcessWithAliases() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->setAlias('b', 'c'); @@ -46,11 +45,9 @@ class CheckCircularReferencesPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testProcessWithFactory() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container @@ -64,11 +61,9 @@ class CheckCircularReferencesPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testProcessDetectsIndirectCircularReference() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('c')); @@ -77,11 +72,9 @@ class CheckCircularReferencesPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testProcessDetectsIndirectCircularReferenceWithFactory() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); @@ -95,11 +88,9 @@ class CheckCircularReferencesPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testDeepCircularReference() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('c')); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.php index e1dd60b662..26bb1851d4 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.php @@ -12,27 +12,26 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Compiler\CheckDefinitionValidityPass; use Symfony\Component\DependencyInjection\ContainerBuilder; class CheckDefinitionValidityPassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - */ + use ForwardCompatTestTrait; + public function testProcessDetectsSyntheticNonPublicDefinitions() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $container->register('a')->setSynthetic(true)->setPublic(false); $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - */ public function testProcessDetectsNonSyntheticNonAbstractDefinitionWithoutClass() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $container->register('a')->setSynthetic(false)->setAbstract(false); @@ -65,22 +64,18 @@ class CheckDefinitionValidityPassTest extends TestCase $this->addToAssertionCount(1); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - */ public function testInvalidTags() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $container->register('a', 'class')->addTag('foo', ['bar' => ['baz' => 'baz']]); $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\EnvParameterException - */ public function testDynamicPublicServiceName() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\EnvParameterException'); $container = new ContainerBuilder(); $env = $container->getParameterBag()->get('env(BAR)'); $container->register("foo.$env", 'class')->setPublic(true); @@ -88,11 +83,9 @@ class CheckDefinitionValidityPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\EnvParameterException - */ public function testDynamicPublicAliasName() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\EnvParameterException'); $container = new ContainerBuilder(); $env = $container->getParameterBag()->get('env(BAR)'); $container->setAlias("foo.$env", 'class')->setPublic(true); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php index baedabf8d4..1bc522fe26 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\BoundArgument; use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; use Symfony\Component\DependencyInjection\Compiler\CheckExceptionOnInvalidReferenceBehaviorPass; @@ -23,6 +24,8 @@ use Symfony\Component\DependencyInjection\Reference; class CheckExceptionOnInvalidReferenceBehaviorPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testProcess() { $container = new ContainerBuilder(); @@ -38,11 +41,9 @@ class CheckExceptionOnInvalidReferenceBehaviorPassTest extends TestCase $this->addToAssertionCount(1); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - */ public function testProcessThrowsExceptionOnInvalidReference() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); $container = new ContainerBuilder(); $container @@ -53,11 +54,9 @@ class CheckExceptionOnInvalidReferenceBehaviorPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - */ public function testProcessThrowsExceptionOnInvalidReferenceFromInlinedDefinition() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); $container = new ContainerBuilder(); $def = new Definition(); @@ -85,12 +84,10 @@ class CheckExceptionOnInvalidReferenceBehaviorPassTest extends TestCase $this->addToAssertionCount(1); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage The service "foo" in the container provided to "bar" has a dependency on a non-existent service "baz". - */ public function testWithErroredServiceLocator() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $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'); @@ -100,12 +97,10 @@ class CheckExceptionOnInvalidReferenceBehaviorPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage The service "bar" has a dependency on a non-existent service "foo". - */ public function testWithErroredHiddenService() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $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'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckReferenceValidityPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckReferenceValidityPassTest.php index 22b6fd1542..6ac8630b2a 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckReferenceValidityPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckReferenceValidityPassTest.php @@ -12,17 +12,18 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Compiler\CheckReferenceValidityPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; class CheckReferenceValidityPassTest extends TestCase { - /** - * @expectedException \RuntimeException - */ + use ForwardCompatTestTrait; + public function testProcessDetectsReferenceToAbstractDefinition() { + $this->expectException('RuntimeException'); $container = new ContainerBuilder(); $container->register('a')->setAbstract(true); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/DefinitionErrorExceptionPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/DefinitionErrorExceptionPassTest.php index ce6f0496e0..528e883dc5 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/DefinitionErrorExceptionPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/DefinitionErrorExceptionPassTest.php @@ -12,18 +12,19 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Compiler\DefinitionErrorExceptionPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; class DefinitionErrorExceptionPassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Things went wrong! - */ + use ForwardCompatTestTrait; + public function testThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Things went wrong!'); $container = new ContainerBuilder(); $def = new Definition(); $def->addError('Things went wrong!'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php index 61df0ebfa5..64bf948d1c 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; @@ -22,6 +23,8 @@ use Symfony\Component\DependencyInjection\Reference; class InlineServiceDefinitionsPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testProcess() { $container = new ContainerBuilder(); @@ -112,12 +115,10 @@ class InlineServiceDefinitionsPassTest extends TestCase $this->assertEquals(new Reference('bar'), $container->getDefinition('foo')->getArgument(0)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - * @expectedExceptionMessage Circular reference detected for service "bar", path: "bar -> foo -> bar". - */ public function testProcessThrowsOnNonSharedLoops() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); + $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> foo -> bar".'); $container = new ContainerBuilder(); $container ->register('foo') diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/MergeExtensionConfigurationPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/MergeExtensionConfigurationPassTest.php index a254ba99d8..789544dd24 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/MergeExtensionConfigurationPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/MergeExtensionConfigurationPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Config\Resource\FileResource; @@ -23,6 +24,8 @@ use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; class MergeExtensionConfigurationPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testExpressionLanguageProviderForwarding() { $tmpProviders = []; @@ -102,12 +105,10 @@ class MergeExtensionConfigurationPassTest extends TestCase $this->assertSame(['BAZ' => 1, 'FOO' => 0], $container->getEnvCounters()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Using a cast in "env(int:FOO)" is incompatible with resolution at compile time in "Symfony\Component\DependencyInjection\Tests\Compiler\BarExtension". The logic in the extension should be moved to a compiler pass, or an env parameter with no cast should be used instead. - */ public function testProcessedEnvsAreIncompatibleWithResolve() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Using a cast in "env(int:FOO)" is incompatible with resolution at compile time in "Symfony\Component\DependencyInjection\Tests\Compiler\BarExtension". The logic in the extension should be moved to a compiler pass, or an env parameter with no cast should be used instead.'); $container = new ContainerBuilder(); $container->registerExtension(new BarExtension()); $container->prependExtensionConfig('bar', []); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php index add95a98b2..aac5d987a6 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php @@ -12,12 +12,15 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Compiler\RegisterEnvVarProcessorsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\EnvVarProcessorInterface; class RegisterEnvVarProcessorsPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testSimpleProcessor() { $container = new ContainerBuilder(); @@ -60,12 +63,10 @@ class RegisterEnvVarProcessorsPassTest extends TestCase $this->assertFalse($container->has('container.env_var_processors_locator')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid type "foo" returned by "Symfony\Component\DependencyInjection\Tests\Compiler\BadProcessor::getProvidedTypes()", expected one of "array", "bool", "float", "int", "string". - */ public function testBadProcessor() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid type "foo" returned by "Symfony\Component\DependencyInjection\Tests\Compiler\BadProcessor::getProvidedTypes()", expected one of "array", "bool", "float", "int", "string".'); $container = new ContainerBuilder(); $container->register('foo', BadProcessor::class)->addTag('container.env_var_processor'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterServiceSubscribersPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterServiceSubscribersPassTest.php index 14d542f76a..a2a151fab5 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterServiceSubscribersPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterServiceSubscribersPassTest.php @@ -13,6 +13,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface as PsrContainerInterface; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\Compiler\AutowirePass; use Symfony\Component\DependencyInjection\Compiler\RegisterServiceSubscribersPass; @@ -36,12 +37,12 @@ require_once __DIR__.'/../Fixtures/includes/classes.php'; class RegisterServiceSubscribersPassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Service "foo" must implement interface "Symfony\Contracts\Service\ServiceSubscriberInterface". - */ + use ForwardCompatTestTrait; + public function testInvalidClass() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Service "foo" must implement interface "Symfony\Contracts\Service\ServiceSubscriberInterface".'); $container = new ContainerBuilder(); $container->register('foo', CustomDefinition::class) @@ -52,12 +53,10 @@ class RegisterServiceSubscribersPassTest extends TestCase (new ResolveServiceSubscribersPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The "container.service_subscriber" tag accepts only the "key" and "id" attributes, "bar" given for service "foo". - */ public function testInvalidAttributes() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "container.service_subscriber" tag accepts only the "key" and "id" attributes, "bar" given for service "foo".'); $container = new ContainerBuilder(); $container->register('foo', TestServiceSubscriber::class) @@ -126,12 +125,10 @@ class RegisterServiceSubscribersPassTest extends TestCase $this->assertEquals($expected, $container->getDefinition((string) $locator->getFactory()[0])->getArgument(0)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Service key "test" does not exist in the map returned by "Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber::getSubscribedServices()" for service "foo_service". - */ public function testExtraServiceSubscriber() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Service key "test" does not exist in the map returned by "Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber::getSubscribedServices()" for service "foo_service".'); $container = new ContainerBuilder(); $container->register('foo_service', TestServiceSubscriber::class) ->setAutowired(true) diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.php index f9c755c35e..a924d2629f 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Compiler\ReplaceAliasByActualDefinitionPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; @@ -21,6 +22,8 @@ require_once __DIR__.'/../Fixtures/includes/foo.php'; class ReplaceAliasByActualDefinitionPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testProcess() { $container = new ContainerBuilder(); @@ -53,11 +56,9 @@ class ReplaceAliasByActualDefinitionPassTest extends TestCase $this->assertSame('b_alias', (string) $resolvedFactory[0]); } - /** - * @expectedException \InvalidArgumentException - */ public function testProcessWithInvalidAlias() { + $this->expectException('InvalidArgumentException'); $container = new ContainerBuilder(); $container->setAlias('a_alias', 'a'); $this->process($container); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveBindingsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveBindingsPassTest.php index 4f23444844..a7fe5f1914 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveBindingsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveBindingsPassTest.php @@ -13,6 +13,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\Warning; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\BoundArgument; use Symfony\Component\DependencyInjection\Compiler\AutowireRequiredMethodsPass; use Symfony\Component\DependencyInjection\Compiler\ResolveBindingsPass; @@ -28,6 +29,8 @@ require_once __DIR__.'/../Fixtures/includes/autowiring_classes.php'; class ResolveBindingsPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testProcess() { $container = new ContainerBuilder(); @@ -49,12 +52,10 @@ class ResolveBindingsPassTest extends TestCase $this->assertEquals([['setSensitiveClass', [new Reference('foo')]]], $definition->getMethodCalls()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage A binding is configured for an argument named "$quz" for service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy", but no corresponding argument has been found. It may be unused and should be removed, or it may have a typo. - */ public function testUnusedBinding() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('A binding is configured for an argument named "$quz" for service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy", but no corresponding argument has been found. It may be unused and should be removed, or it may have a typo.'); $container = new ContainerBuilder(); $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class); @@ -64,12 +65,10 @@ class ResolveBindingsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegexp Unused binding "$quz" in service [\s\S]+ Invalid service ".*\\ParentNotExists": class NotExists not found\. - */ public function testMissingParent() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('A binding is configured for an argument named "$quz" for service "Symfony\Component\DependencyInjection\Tests\Fixtures\ParentNotExists", but no corresponding argument has been found. It may be unused and should be removed, or it may have a typo.'); if (\PHP_VERSION_ID >= 70400) { throw new Warning('PHP 7.4 breaks this test, see https://bugs.php.net/78351.'); } @@ -118,12 +117,10 @@ class ResolveBindingsPassTest extends TestCase $this->assertEquals([['setDefaultLocale', ['fr']]], $definition->getMethodCalls()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @exceptedExceptionMessage Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "setLogger()" does not exist. - */ public function testWithNonExistingSetterAndBinding() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "setLogger()" does not exist.'); $container = new ContainerBuilder(); $bindings = [ diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveChildDefinitionsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveChildDefinitionsPassTest.php index 07c1abdf5d..18be3ae21f 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveChildDefinitionsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveChildDefinitionsPassTest.php @@ -12,12 +12,15 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; class ResolveChildDefinitionsPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testProcess() { $container = new ContainerBuilder(); @@ -397,12 +400,10 @@ class ResolveChildDefinitionsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - * @expectedExceptionMessageRegExp /^Circular reference detected for service "c", path: "c -> b -> a -> c"./ - */ public function testProcessDetectsChildDefinitionIndirectCircularReference() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); + $this->expectExceptionMessageRegExp('/^Circular reference detected for service "c", path: "c -> b -> a -> c"./'); $container = new ContainerBuilder(); $container->register('a'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveClassPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveClassPassTest.php index 48df3843dc..e791ceae08 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveClassPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveClassPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\Compiler\ResolveClassPass; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -19,6 +20,8 @@ use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass; class ResolveClassPassTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider provideValidClassId */ @@ -82,12 +85,10 @@ class ResolveClassPassTest extends TestCase $this->assertSame(self::class, $child->getClass()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Service definition "App\Foo\Child" has a parent but no class, and its name looks like a FQCN. Either the class is missing or you want to inherit it from the parent service. To resolve this ambiguity, please rename this service to a non-FQCN (e.g. using dots), or create the missing class. - */ public function testAmbiguousChildDefinition() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Service definition "App\Foo\Child" has a parent but no class, and its name looks like a FQCN. Either the class is missing or you want to inherit it from the parent service. To resolve this ambiguity, please rename this service to a non-FQCN (e.g. using dots), or create the missing class.'); $container = new ContainerBuilder(); $parent = $container->register('App\Foo', null); $child = $container->setDefinition('App\Foo\Child', new ChildDefinition('App\Foo')); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveFactoryClassPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveFactoryClassPassTest.php index 3438fad068..8511172fb0 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveFactoryClassPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveFactoryClassPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Compiler\ResolveFactoryClassPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; @@ -19,6 +20,8 @@ use Symfony\Component\DependencyInjection\Reference; class ResolveFactoryClassPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testProcess() { $container = new ContainerBuilder(); @@ -71,12 +74,10 @@ class ResolveFactoryClassPassTest extends TestCase $this->assertSame($factory, $container->getDefinition('factory')->getFactory()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The "factory" service is defined to be created by a factory, but is missing the factory class. Did you forget to define the factory or service class? - */ public function testNotAnyClassThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The "factory" service is defined to be created by a factory, but is missing the factory class. Did you forget to define the factory or service class?'); $container = new ContainerBuilder(); $factory = $container->register('factory'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php index 7fee5194f0..e8b36383d6 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\BoundArgument; use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass; @@ -21,6 +22,8 @@ use Symfony\Component\DependencyInjection\Reference; class ResolveInstanceofConditionalsPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testProcess() { $container = new ContainerBuilder(); @@ -173,12 +176,10 @@ class ResolveInstanceofConditionalsPassTest extends TestCase $this->assertFalse($def->isAutowired()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage "App\FakeInterface" is set as an "instanceof" conditional, but it does not exist. - */ public function testBadInterfaceThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('"App\FakeInterface" is set as an "instanceof" conditional, but it does not exist.'); $container = new ContainerBuilder(); $def = $container->register('normal_service', self::class); $def->setInstanceofConditionals([ @@ -232,12 +233,10 @@ class ResolveInstanceofConditionalsPassTest extends TestCase $this->assertEquals($expected, $container->findDefinition('foo')->getMethodCalls()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Autoconfigured instanceof for type "PHPUnit\Framework\TestCase" defines arguments but these are not supported and should be removed. - */ public function testProcessThrowsExceptionForArguments() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Autoconfigured instanceof for type "PHPUnit\Framework\TestCase" defines arguments but these are not supported and should be removed.'); $container = new ContainerBuilder(); $container->registerForAutoconfiguration(parent::class) ->addArgument('bar'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveNamedArgumentsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveNamedArgumentsPassTest.php index d42600d78b..b564784d61 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveNamedArgumentsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveNamedArgumentsPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Compiler\ResolveNamedArgumentsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; @@ -27,6 +28,8 @@ use Symfony\Component\DependencyInjection\Tests\Fixtures\TestDefinition1; */ class ResolveNamedArgumentsPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testProcess() { $container = new ContainerBuilder(); @@ -61,11 +64,9 @@ class ResolveNamedArgumentsPassTest extends TestCase $this->assertSame([0 => '123'], $definition->getArguments()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - */ public function testClassNull() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $definition = $container->register(NamedArgumentsDummy::class); @@ -75,11 +76,9 @@ class ResolveNamedArgumentsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - */ public function testClassNotExist() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $definition = $container->register(NotExist::class, NotExist::class); @@ -89,11 +88,9 @@ class ResolveNamedArgumentsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - */ public function testClassNoConstructor() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $definition = $container->register(NoConstructor::class, NoConstructor::class); @@ -103,12 +100,10 @@ class ResolveNamedArgumentsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "__construct()" has no argument named "$notFound". Check your service definition. - */ public function testArgumentNotFound() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "__construct()" has no argument named "$notFound". Check your service definition.'); $container = new ContainerBuilder(); $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class); @@ -118,12 +113,10 @@ class ResolveNamedArgumentsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\TestDefinition1": method "Symfony\Component\DependencyInjection\Tests\Fixtures\FactoryDummyWithoutReturnTypes::createTestDefinition1()" has no argument named "$notFound". Check your service definition. - */ public function testCorrectMethodReportedInException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\TestDefinition1": method "Symfony\Component\DependencyInjection\Tests\Fixtures\FactoryDummyWithoutReturnTypes::createTestDefinition1()" has no argument named "$notFound". Check your service definition.'); $container = new ContainerBuilder(); $container->register(FactoryDummyWithoutReturnTypes::class, FactoryDummyWithoutReturnTypes::class); @@ -149,12 +142,10 @@ class ResolveNamedArgumentsPassTest extends TestCase $this->assertEquals([new Reference('foo'), '123'], $definition->getArguments()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": did you forget to add the "$" prefix to argument "apiKey"? - */ public function testTypedArgumentWithMissingDollar() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": did you forget to add the "$" prefix to argument "apiKey"?'); $container = new ContainerBuilder(); $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveReferencesToAliasesPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveReferencesToAliasesPassTest.php index c37f9990af..234f86c5a2 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveReferencesToAliasesPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveReferencesToAliasesPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Compiler\ResolveReferencesToAliasesPass; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -20,6 +21,8 @@ use Symfony\Component\DependencyInjection\Reference; class ResolveReferencesToAliasesPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testProcess() { $container = new ContainerBuilder(); @@ -51,11 +54,9 @@ class ResolveReferencesToAliasesPassTest extends TestCase $this->assertEquals('foo', (string) $arguments[0]); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testAliasCircularReference() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container->setAlias('bar', 'foo'); $container->setAlias('foo', 'bar'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ServiceLocatorTagPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ServiceLocatorTagPassTest.php index 27ee7db533..f30c963579 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ServiceLocatorTagPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ServiceLocatorTagPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\BoundArgument; use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -25,12 +26,12 @@ require_once __DIR__.'/../Fixtures/includes/classes.php'; class ServiceLocatorTagPassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid definition for service "foo": an array of references is expected as first argument when the "container.service_locator" tag is set. - */ + use ForwardCompatTestTrait; + public function testNoServices() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid definition for service "foo": an array of references is expected as first argument when the "container.service_locator" tag is set.'); $container = new ContainerBuilder(); $container->register('foo', ServiceLocator::class) @@ -40,12 +41,10 @@ class ServiceLocatorTagPassTest extends TestCase (new ServiceLocatorTagPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid definition for service "foo": an array of references is expected as first argument when the "container.service_locator" tag is set, "string" found for key "0". - */ public function testInvalidServices() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid definition for service "foo": an array of references is expected as first argument when the "container.service_locator" tag is set, "string" found for key "0".'); $container = new ContainerBuilder(); $container->register('foo', ServiceLocator::class) diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php index bfc4b2c56e..2a0ca7840e 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php @@ -42,12 +42,10 @@ class ValidateEnvPlaceholdersPassTest extends TestCase $this->assertSame($expected, $container->resolveEnvPlaceholders($ext->getConfig())); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage Invalid configuration for path "env_extension.string_node": "fail" is not a valid string - */ public function testDefaultEnvIsValidatedInConfig() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('Invalid configuration for path "env_extension.string_node": "fail" is not a valid string'); $container = new ContainerBuilder(); $container->setParameter('env(STRING)', 'fail'); $container->registerExtension($ext = new EnvExtension()); @@ -58,12 +56,11 @@ class ValidateEnvPlaceholdersPassTest extends TestCase $this->doProcess($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The default value of an env() parameter must be a string or null, but "double" given to "env(FLOATISH)". - */ public function testDefaultEnvWithoutPrefixIsValidatedInConfig() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The default value of an env() parameter must be a string or null, but "double" given to "env(FLOATISH)".'); + $container = new ContainerBuilder(); $container->setParameter('env(FLOATISH)', 3.2); $container->registerExtension($ext = new EnvExtension()); @@ -74,12 +71,10 @@ class ValidateEnvPlaceholdersPassTest extends TestCase $this->doProcess($container); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException - * @expectedExceptionMessage Invalid type for path "env_extension.bool_node". Expected "bool", but got one of "bool", "int", "float", "string", "array". - */ public function testEnvsAreValidatedInConfigWithInvalidPlaceholder() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); + $this->expectExceptionMessage('Invalid type for path "env_extension.bool_node". Expected "bool", but got one of "bool", "int", "float", "string", "array".'); $container = new ContainerBuilder(); $container->registerExtension($ext = new EnvExtension()); $container->prependExtensionConfig('env_extension', $expected = [ @@ -91,12 +86,10 @@ class ValidateEnvPlaceholdersPassTest extends TestCase $this->assertSame($expected, $container->resolveEnvPlaceholders($ext->getConfig())); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException - * @expectedExceptionMessage Invalid type for path "env_extension.int_node". Expected "int", but got "array". - */ public function testInvalidEnvInConfig() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); + $this->expectExceptionMessage('Invalid type for path "env_extension.int_node". Expected "int", but got "array".'); $container = new ContainerBuilder(); $container->registerExtension(new EnvExtension()); $container->prependExtensionConfig('env_extension', [ @@ -106,12 +99,10 @@ class ValidateEnvPlaceholdersPassTest extends TestCase $this->doProcess($container); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException - * @expectedExceptionMessage Invalid type for path "env_extension.int_node". Expected int, but got NULL. - */ public function testNulledEnvInConfig() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); + $this->expectExceptionMessage('Invalid type for path "env_extension.int_node". Expected int, but got NULL.'); $container = new ContainerBuilder(); $container->setParameter('env(NULLED)', null); $container->registerExtension(new EnvExtension()); @@ -160,12 +151,10 @@ class ValidateEnvPlaceholdersPassTest extends TestCase $this->assertSame(['scalar_node' => $expected], $container->resolveEnvPlaceholders($ext->getConfig())); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage A dynamic value is not compatible with a "Symfony\Component\Config\Definition\EnumNode" node type at path "env_extension.enum_node". - */ public function testEnvIsIncompatibleWithEnumNode() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('A dynamic value is not compatible with a "Symfony\Component\Config\Definition\EnumNode" node type at path "env_extension.enum_node".'); $container = new ContainerBuilder(); $container->registerExtension(new EnvExtension()); $container->prependExtensionConfig('env_extension', [ @@ -175,12 +164,10 @@ class ValidateEnvPlaceholdersPassTest extends TestCase $this->doProcess($container); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage A dynamic value is not compatible with a "Symfony\Component\Config\Definition\ArrayNode" node type at path "env_extension.simple_array_node". - */ public function testEnvIsIncompatibleWithArrayNode() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('A dynamic value is not compatible with a "Symfony\Component\Config\Definition\ArrayNode" node type at path "env_extension.simple_array_node".'); $container = new ContainerBuilder(); $container->registerExtension(new EnvExtension()); $container->prependExtensionConfig('env_extension', [ @@ -229,12 +216,11 @@ class ValidateEnvPlaceholdersPassTest extends TestCase $this->assertSame($expected, $container->resolveEnvPlaceholders($ext->getConfig())); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The path "env_extension.scalar_node_not_empty_validated" cannot contain an environment variable when empty values are not allowed by definition and are validated. - */ public function testEmptyEnvWhichCannotBeEmptyForScalarNodeWithValidation(): void { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('The path "env_extension.scalar_node_not_empty_validated" cannot contain an environment variable when empty values are not allowed by definition and are validated.'); + if (!method_exists(ParentNodeDefinitionInterface::class, 'getChildNodeDefinitions')) { $this->markTestSkipped('symfony/config >=5.0 is required.'); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php b/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php index a8855b7873..8e1183f34f 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php @@ -134,12 +134,10 @@ class ContainerBuilderTest extends TestCase $this->assertTrue($builder->has('bar'), '->has() returns true if a service exists'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage You have requested a non-existent service "foo". - */ public function testGetThrowsExceptionIfServiceDoesNotExist() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $this->expectExceptionMessage('You have requested a non-existent service "foo".'); $builder = new ContainerBuilder(); $builder->get('foo'); } @@ -151,11 +149,9 @@ class ContainerBuilderTest extends TestCase $this->assertNull($builder->get('foo', ContainerInterface::NULL_ON_INVALID_REFERENCE), '->get() returns null if the service does not exist and NULL_ON_INVALID_REFERENCE is passed as a second argument'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testGetThrowsCircularReferenceExceptionIfServiceHasReferenceToItself() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $builder = new ContainerBuilder(); $builder->register('baz', 'stdClass')->setArguments([new Reference('baz')]); $builder->get('baz'); @@ -203,21 +199,21 @@ class ContainerBuilderTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException * @dataProvider provideBadId */ public function testBadAliasId($id) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $builder = new ContainerBuilder(); $builder->setAlias($id, 'foo'); } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException * @dataProvider provideBadId */ public function testBadDefinitionId($id) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $builder = new ContainerBuilder(); $builder->setDefinition($id, new Definition('Foo')); } @@ -234,12 +230,10 @@ class ContainerBuilderTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage You have requested a synthetic service ("foo"). The DIC does not know how to construct this service. - */ public function testGetUnsetLoadingServiceWhenCreateServiceThrowsAnException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('You have requested a synthetic service ("foo"). The DIC does not know how to construct this service.'); $builder = new ContainerBuilder(); $builder->register('foo', 'stdClass')->setSynthetic(true); @@ -534,11 +528,9 @@ class ContainerBuilderTest extends TestCase $this->assertEquals(0, $i); } - /** - * @expectedException \RuntimeException - */ public function testCreateSyntheticService() { + $this->expectException('RuntimeException'); $builder = new ContainerBuilder(); $builder->register('foo', 'Bar\FooClass')->setSynthetic(true); $builder->get('foo'); @@ -562,12 +554,10 @@ class ContainerBuilderTest extends TestCase $this->assertEquals($builder->get('foo'), $builder->resolveServices(new Expression('service("foo")')), '->resolveServices() resolves expressions'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Constructing service "foo" from a parent definition is not supported at build time. - */ public function testResolveServicesWithDecoratedDefinition() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $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')); @@ -643,12 +633,10 @@ class ContainerBuilderTest extends TestCase $this->assertSame(['AInterface' => $childDefA, 'BInterface' => $childDefB], $container->getAutoconfiguredInstanceof()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage "AInterface" has already been autoconfigured and merge() does not support merging autoconfiguration for the same class/interface. - */ public function testMergeThrowsExceptionForDuplicateAutomaticInstanceofDefinitions() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $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'); @@ -750,12 +738,10 @@ class ContainerBuilderTest extends TestCase putenv('ARRAY'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage 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)%". - */ public function testCompileWithArrayInStringResolveEnv() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $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(); @@ -765,12 +751,10 @@ class ContainerBuilderTest extends TestCase putenv('ARRAY'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\EnvNotFoundException - * @expectedExceptionMessage Environment variable not found: "FOO". - */ public function testCompileWithResolveMissingEnv() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\EnvNotFoundException'); + $this->expectExceptionMessage('Environment variable not found: "FOO".'); $container = new ContainerBuilder(); $container->setParameter('foo', '%env(FOO)%'); $container->compile(true); @@ -863,12 +847,10 @@ class ContainerBuilderTest extends TestCase $this->assertSame(['baz_bar'], array_keys($container->getDefinition('foo')->getArgument(1))); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException - * @expectedExceptionMessage Circular reference detected for parameter "env(resolve:DUMMY_ENV_VAR)" ("env(resolve:DUMMY_ENV_VAR)" > "env(resolve:DUMMY_ENV_VAR)"). - */ public function testCircularDynamicEnv() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException'); + $this->expectExceptionMessage('Circular reference detected for parameter "env(resolve:DUMMY_ENV_VAR)" ("env(resolve:DUMMY_ENV_VAR)" > "env(resolve:DUMMY_ENV_VAR)").'); putenv('DUMMY_ENV_VAR=some%foo%'); $container = new ContainerBuilder(); @@ -882,11 +864,9 @@ class ContainerBuilderTest extends TestCase } } - /** - * @expectedException \LogicException - */ public function testMergeLogicException() { + $this->expectException('LogicException'); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->compile(); @@ -1110,11 +1090,9 @@ class ContainerBuilderTest extends TestCase $this->assertInstanceOf('BarClass', $container->get('bar_user')->bar); } - /** - * @expectedException \BadMethodCallException - */ public function testThrowsExceptionWhenSetServiceOnACompiledContainer() { + $this->expectException('BadMethodCallException'); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->register('a', 'stdClass')->setPublic(true); @@ -1141,11 +1119,9 @@ class ContainerBuilderTest extends TestCase $this->assertEquals($a, $container->get('a')); } - /** - * @expectedException \BadMethodCallException - */ public function testThrowsExceptionWhenSetDefinitionOnACompiledContainer() { + $this->expectException('BadMethodCallException'); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->compile(); @@ -1237,12 +1213,10 @@ class ContainerBuilderTest extends TestCase $this->assertNotSame($bar->foo, $barUser->foo); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - * @expectedExceptionMessage Circular reference detected for service "app.test_class", path: "app.test_class -> App\TestClass -> app.test_class". - */ public function testThrowsCircularExceptionForCircularAliases() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); + $this->expectExceptionMessage('Circular reference detected for service "app.test_class", path: "app.test_class -> App\TestClass -> app.test_class".'); $builder = new ContainerBuilder(); $builder->setAliases([ @@ -1295,60 +1269,50 @@ class ContainerBuilderTest extends TestCase $this->assertEquals(CaseSensitiveClass::class, $autoloadClass->getClass()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The definition for "DateTime" has no class attribute, and appears to reference a class or interface in the global namespace. - */ public function testNoClassFromGlobalNamespaceClassId() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The definition for "DateTime" has no class attribute, and appears to reference a class or interface in the global namespace.'); $container = new ContainerBuilder(); $definition = $container->register(\DateTime::class); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The definition for "\DateTime" has no class attribute, and appears to reference a class or interface in the global namespace. - */ public function testNoClassFromGlobalNamespaceClassIdWithLeadingSlash() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The definition for "\DateTime" has no class attribute, and appears to reference a class or interface in the global namespace.'); $container = new ContainerBuilder(); $container->register('\\'.\DateTime::class); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage 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. - */ public function testNoClassFromNamespaceClassIdWithLeadingSlash() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $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); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The definition for "123_abc" has no class. - */ public function testNoClassFromNonClassId() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The definition for "123_abc" has no class.'); $container = new ContainerBuilder(); $definition = $container->register('123_abc'); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The definition for "\foo" has no class. - */ public function testNoClassFromNsSeparatorId() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The definition for "\foo" has no class.'); $container = new ContainerBuilder(); $definition = $container->register('\\foo'); @@ -1554,12 +1518,10 @@ class ContainerBuilderTest extends TestCase $container->removeDefinition($id); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Service "errored_definition" is broken. - */ public function testErroredDefinition() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Service "errored_definition" is broken.'); $container = new ContainerBuilder(); $container->register('errored_definition', 'stdClass') diff --git a/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php b/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php index 21d42cc968..64132d0dbe 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\ContainerInterface; @@ -21,6 +22,8 @@ use Symfony\Contracts\Service\ResetInterface; class ContainerTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $sc = new Container(); @@ -166,12 +169,10 @@ class ContainerTest extends TestCase $this->assertSame($foo, $c->get('alias'), '->set() replaces an existing alias'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The "bar" service is already initialized, you cannot replace it. - */ public function testSetWithNullOnInitializedPredefinedService() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "bar" service is already initialized, you cannot replace it.'); $sc = new Container(); $sc->set('foo', new \stdClass()); $sc->set('foo', null); @@ -260,24 +261,20 @@ class ContainerTest extends TestCase } } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage The "request" service is synthetic, it needs to be set at boot time before it can be used. - */ public function testGetSyntheticServiceThrows() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $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(); $container->get('request'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage 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. - */ public function testGetRemovedServiceThrows() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $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(); @@ -343,12 +340,10 @@ class ContainerTest extends TestCase $this->assertSame(1, $bar->resetCounter); } - /** - * @expectedException \Exception - * @expectedExceptionMessage Something went terribly wrong! - */ public function testGetThrowsException() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Something went terribly wrong!'); $c = new ProjectServiceContainer(); try { @@ -413,12 +408,10 @@ class ContainerTest extends TestCase $this->assertFalse($c->has('internal')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage You have requested a non-existent service "internal". - */ public function testRequestAnInternalSharedPrivateService() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $this->expectExceptionMessage('You have requested a non-existent service "internal".'); $c = new ProjectServiceContainer(); $c->get('internal_dependency'); $c->get('internal'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/DefinitionTest.php b/src/Symfony/Component/DependencyInjection/Tests/DefinitionTest.php index 72ffaf5803..5e856fd2dd 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/DefinitionTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/DefinitionTest.php @@ -110,12 +110,10 @@ class DefinitionTest extends TestCase $this->assertEquals([['foobar', ['foobar'], true]], $def->getMethodCalls(), '->addMethodCall() adds a method to call'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Method name cannot be empty. - */ public function testExceptionOnEmptyMethodCall() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Method name cannot be empty.'); $def = new Definition('stdClass'); $def->addMethodCall(''); } @@ -180,10 +178,10 @@ class DefinitionTest extends TestCase /** * @dataProvider invalidDeprecationMessageProvider - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException */ public function testSetDeprecatedWithInvalidDeprecationTemplate($message) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $def = new Definition('stdClass'); $def->setDeprecated(false, $message); } @@ -266,35 +264,29 @@ class DefinitionTest extends TestCase $this->assertSame(['foo', 'bar'], $def->getArguments()); } - /** - * @expectedException \OutOfBoundsException - */ public function testGetArgumentShouldCheckBounds() { + $this->expectException('OutOfBoundsException'); $def = new Definition('stdClass'); $def->addArgument('foo'); $def->getArgument(1); } - /** - * @expectedException \OutOfBoundsException - * @expectedExceptionMessage The index "1" is not in the range [0, 0]. - */ public function testReplaceArgumentShouldCheckBounds() { + $this->expectException('OutOfBoundsException'); + $this->expectExceptionMessage('The index "1" is not in the range [0, 0].'); $def = new Definition('stdClass'); $def->addArgument('foo'); $def->replaceArgument(1, 'bar'); } - /** - * @expectedException \OutOfBoundsException - * @expectedExceptionMessage Cannot replace arguments if none have been configured yet. - */ public function testReplaceArgumentWithoutExistingArgumentsShouldCheckBounds() { + $this->expectException('OutOfBoundsException'); + $this->expectExceptionMessage('Cannot replace arguments if none have been configured yet.'); $def = new Definition('stdClass'); $def->replaceArgument(0, 'bar'); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php index f08fc879ca..c33901fdd8 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php @@ -161,10 +161,10 @@ class PhpDumperTest extends TestCase /** * @dataProvider provideInvalidParameters - * @expectedException \InvalidArgumentException */ public function testExportParameters($parameters) { + $this->expectException('InvalidArgumentException'); $container = new ContainerBuilder(new ParameterBag($parameters)); $container->compile(); $dumper = new PhpDumper($container); @@ -189,12 +189,10 @@ class PhpDumperTest extends TestCase $this->assertStringEqualsFile(self::$fixturesPath.'/php/services8.php', $dumper->dump(), '->dump() dumps parameters'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException - * @expectedExceptionMessage Cannot dump an uncompiled container. - */ public function testAddServiceWithoutCompilation() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException'); + $this->expectExceptionMessage('Cannot dump an uncompiled container.'); $container = include self::$fixturesPath.'/containers/container9.php'; new PhpDumper($container); } @@ -374,11 +372,11 @@ class PhpDumperTest extends TestCase /** * @dataProvider provideInvalidFactories - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Cannot dump definition */ public function testInvalidFactories($factory) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Cannot dump definition'); $container = new ContainerBuilder(); $def = new Definition('stdClass'); $def->setPublic(true); @@ -443,12 +441,10 @@ class PhpDumperTest extends TestCase $this->assertFalse($container->has('foo')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The "decorator_service" service is already initialized, you cannot replace it. - */ public function testOverrideServiceWhenUsingADumpedContainer() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "decorator_service" service is already initialized, you cannot replace it.'); require_once self::$fixturesPath.'/php/services9_compiled.php'; $container = new \ProjectServiceContainer(); @@ -662,12 +658,10 @@ class PhpDumperTest extends TestCase $this->assertStringEqualsFile(__FILE__, $container->getParameter('random')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\EnvParameterException - * @expectedExceptionMessage Environment variables "FOO" are never used. Please, check your container's configuration. - */ public function testUnusedEnvParameter() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\EnvParameterException'); + $this->expectExceptionMessage('Environment variables "FOO" are never used. Please, check your container\'s configuration.'); $container = new ContainerBuilder(); $container->getParameter('env(FOO)'); $container->compile(); @@ -675,12 +669,10 @@ class PhpDumperTest extends TestCase $dumper->dump(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException - * @expectedExceptionMessage Circular reference detected for parameter "env(resolve:DUMMY_ENV_VAR)" ("env(resolve:DUMMY_ENV_VAR)" > "env(resolve:DUMMY_ENV_VAR)"). - */ public function testCircularDynamicEnv() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException'); + $this->expectExceptionMessage('Circular reference detected for parameter "env(resolve:DUMMY_ENV_VAR)" ("env(resolve:DUMMY_ENV_VAR)" > "env(resolve:DUMMY_ENV_VAR)").'); $container = new ContainerBuilder(); $container->setParameter('foo', '%bar%'); $container->setParameter('bar', '%env(resolve:DUMMY_ENV_VAR)%'); @@ -1244,12 +1236,10 @@ class PhpDumperTest extends TestCase $this->assertSame('foo', $container->getParameter('BAR')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Service "errored_definition" is broken. - */ public function testErroredDefinition() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Service "errored_definition" is broken.'); $container = include self::$fixturesPath.'/containers/container9.php'; $container->setParameter('foo_bar', 'foo_bar'); $container->compile(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php b/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php index 5aa905d954..242bfa85be 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php @@ -3,12 +3,15 @@ namespace Symfony\Component\DependencyInjection\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\EnvVarProcessor; class EnvVarProcessorTest extends TestCase { + use ForwardCompatTestTrait; + const TEST_CONST = 'test'; /** @@ -98,12 +101,12 @@ class EnvVarProcessorTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Non-numeric env var * @dataProvider invalidInts */ public function testGetEnvIntInvalid($value) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Non-numeric env var'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('int', 'foo', function ($name) use ($value) { @@ -148,12 +151,12 @@ class EnvVarProcessorTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Non-numeric env var * @dataProvider invalidFloats */ public function testGetEnvFloatInvalid($value) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Non-numeric env var'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('float', 'foo', function ($name) use ($value) { @@ -197,12 +200,12 @@ class EnvVarProcessorTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage undefined constant * @dataProvider invalidConsts */ public function testGetEnvConstInvalid($value) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('undefined constant'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('const', 'foo', function ($name) use ($value) { @@ -271,12 +274,10 @@ class EnvVarProcessorTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Syntax error - */ public function testGetEnvInvalidJson() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Syntax error'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('json', 'foo', function ($name) { @@ -287,12 +288,12 @@ class EnvVarProcessorTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid JSON env var * @dataProvider otherJsonValues */ public function testGetEnvJsonOther($value) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid JSON env var'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('json', 'foo', function ($name) use ($value) { @@ -313,12 +314,10 @@ class EnvVarProcessorTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Unsupported env var prefix - */ public function testGetEnvUnknown() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Unsupported env var prefix'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('unknown', 'foo', function ($name) { @@ -328,12 +327,10 @@ class EnvVarProcessorTest extends TestCase }); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid env "key:foo": a key specifier should be provided. - */ public function testGetEnvKeyInvalidKey() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid env "key:foo": a key specifier should be provided.'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('key', 'foo', function ($name) { @@ -342,12 +339,12 @@ class EnvVarProcessorTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Resolved value of "foo" did not result in an array value. * @dataProvider noArrayValues */ public function testGetEnvKeyNoArrayResult($value) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $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) { @@ -368,12 +365,12 @@ class EnvVarProcessorTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\EnvNotFoundException - * @expectedExceptionMessage Key "index" not found in * @dataProvider invalidArrayValues */ public function testGetEnvKeyArrayKeyNotFound($value) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\EnvNotFoundException'); + $this->expectExceptionMessage('Key "index" not found in'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('key', 'index:foo', function ($name) use ($value) { @@ -459,12 +456,10 @@ class EnvVarProcessorTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\EnvNotFoundException - * @expectedExceptionMessage missing-file - */ public function testRequireMissingFile() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\EnvNotFoundException'); + $this->expectExceptionMessage('missing-file'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('require', '/missing-file', function ($name) { diff --git a/src/Symfony/Component/DependencyInjection/Tests/Extension/ExtensionTest.php b/src/Symfony/Component/DependencyInjection/Tests/Extension/ExtensionTest.php index a57b0576a4..955e97f582 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Extension/ExtensionTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Extension/ExtensionTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Extension; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\Tests\Fixtures\Extension\InvalidConfig\InvalidConfigExtension; @@ -21,6 +22,8 @@ use Symfony\Component\DependencyInjection\Tests\Fixtures\Extension\ValidConfig\V class ExtensionTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getResolvedEnabledFixtures */ @@ -38,12 +41,10 @@ class ExtensionTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The config array has no 'enabled' key. - */ public function testIsConfigEnabledOnNonEnableableConfig() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The config array has no \'enabled\' key.'); $extension = new EnableableExtension(); $extension->isConfigEnabled(new ContainerBuilder(), []); @@ -70,12 +71,11 @@ class ExtensionTest extends TestCase $this->assertNull($extension->getConfiguration([], new ContainerBuilder())); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException - * @expectedExceptionMessage The extension configuration class "Symfony\Component\DependencyInjection\Tests\Fixtures\Extension\InvalidConfig\Configuration" must implement "Symfony\Component\Config\Definition\ConfigurationInterface". - */ public function testInvalidConfiguration() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException'); + $this->expectExceptionMessage('The extension configuration class "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\Extension\\InvalidConfig\\Configuration" must implement "Symfony\\Component\\Config\\Definition\\ConfigurationInterface".'); + $extension = new InvalidConfigExtension(); $extension->getConfiguration([], new ContainerBuilder()); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/DirectoryLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/DirectoryLoaderTest.php index 8de0b7d0de..59f7e9ad39 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/DirectoryLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/DirectoryLoaderTest.php @@ -61,12 +61,10 @@ class DirectoryLoaderTest extends TestCase $this->assertEquals(['ini' => 'ini', 'yaml' => 'yaml'], $this->container->getParameterBag()->all(), '->load() takes a single file that imports a directory'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The file "foo" does not exist (in: - */ public function testExceptionIsRaisedWhenDirectoryDoesNotExist() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The file "foo" does not exist (in:'); $this->loader->load('foo/'); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php index 2e2de0b5cf..3f8d3daf14 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php @@ -218,12 +218,10 @@ class FileLoaderTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /Expected to find class "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\Prototype\\Bar" in file ".+" while importing services from resource "Prototype\/Sub\/\*", but it was not found\! Check the namespace prefix used with the resource/ - */ public function testRegisterClassesWithBadPrefix() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Expected to find class "Symfony\\\Component\\\DependencyInjection\\\Tests\\\Fixtures\\\Prototype\\\Bar" in file ".+" while importing services from resource "Prototype\/Sub\/\*", but it was not found\! Check the namespace prefix used with the resource/'); $container = new ContainerBuilder(); $loader = new TestFileLoader($container, new FileLocator(self::$fixturesPath.'/Fixtures')); @@ -231,12 +229,10 @@ class FileLoaderTest extends TestCase $loader->registerClasses(new Definition(), 'Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\\', 'Prototype/Sub/*'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid "exclude" pattern when importing classes for "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\": make sure your "exclude" pattern (yaml/*) is a subset of the "resource" pattern (Prototype/*) - */ public function testRegisterClassesWithIncompatibleExclude() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid "exclude" pattern when importing classes for "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\": make sure your "exclude" pattern (yaml/*) is a subset of the "resource" pattern (Prototype/*)'); $container = new ContainerBuilder(); $loader = new TestFileLoader($container, new FileLocator(self::$fixturesPath.'/Fixtures')); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.php index ac3b38a64c..7514198e0c 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.php @@ -93,30 +93,24 @@ class IniFileLoaderTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The file "foo.ini" does not exist (in: - */ public function testExceptionIsRaisedWhenIniFileDoesNotExist() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The file "foo.ini" does not exist (in:'); $this->loader->load('foo.ini'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The "nonvalid.ini" file is not valid. - */ public function testExceptionIsRaisedWhenIniFileCannotBeParsed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "nonvalid.ini" file is not valid.'); @$this->loader->load('nonvalid.ini'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The "almostvalid.ini" file is not valid. - */ public function testExceptionIsRaisedWhenIniFileIsAlmostValid() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "almostvalid.ini" file is not valid.'); @$this->loader->load('almostvalid.ini'); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.php index 48791706a7..26f72199f4 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Dumper\PhpDumper; @@ -20,6 +21,8 @@ use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; class PhpFileLoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testSupports() { $loader = new PhpFileLoader(new ContainerBuilder(), new FileLocator()); @@ -79,12 +82,10 @@ class PhpFileLoaderTest extends TestCase yield ['lazy_fqcn']; } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The service "child_service" cannot have a "parent" and also have "autoconfigure". Try disabling autoconfiguration for the service. - */ public function testAutoConfigureAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The service "child_service" cannot have a "parent" and also have "autoconfigure". Try disabling autoconfiguration for the service.'); $fixtures = realpath(__DIR__.'/../Fixtures'); $container = new ContainerBuilder(); $loader = new PhpFileLoader($container, new FileLocator()); @@ -92,12 +93,10 @@ class PhpFileLoaderTest extends TestCase $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid factory "factory:method": the "service:method" notation is not available when using PHP-based DI configuration. Use "[ref('factory'), 'method']" instead. - */ public function testFactoryShortNotationNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid factory "factory:method": the "service:method" notation is not available when using PHP-based DI configuration. Use "[ref(\'factory\'), \'method\']" instead.'); $fixtures = realpath(__DIR__.'/../Fixtures'); $container = new ContainerBuilder(); $loader = new PhpFileLoader($container, new FileLocator()); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php index 0a5ac45a8f..a167032ab8 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php @@ -230,12 +230,10 @@ class XmlFileLoaderTest extends TestCase $this->assertSame($fooArgs[0], $barArgs[0]); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Top-level services must have "id" attribute, none found in - */ public function testLoadAnonymousServicesWithoutId() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Top-level services must have "id" attribute, none found in'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_without_id.xml'); @@ -339,22 +337,18 @@ class XmlFileLoaderTest extends TestCase $this->assertEquals(new ServiceLocatorArgument($taggedIterator), $container->getDefinition('foo_tagged_locator')->getArgument(0)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - */ public function testParseTagsWithoutNameThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('tag_without_name.xml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /The tag name for service ".+" in .* must be a non-empty string/ - */ public function testParseTagWithEmptyNameThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The tag name for service ".+" in .* must be a non-empty string/'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('tag_with_empty_name.xml'); @@ -701,12 +695,10 @@ class XmlFileLoaderTest extends TestCase $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar', $resources); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid attribute "class" defined for alias "bar" in - */ public function testAliasDefinitionContainsUnsupportedElements() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid attribute "class" defined for alias "bar" in'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); @@ -786,36 +778,30 @@ class XmlFileLoaderTest extends TestCase $this->assertSame(['foo' => [[]], 'bar' => [[]]], $definition->getTags()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The service "child_service" cannot use the "parent" option in the same file where "instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file. - */ public function testInstanceOfAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The service "child_service" cannot use the "parent" option in the same file where "instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file.'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_instanceof_with_parent.xml'); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The service "child_service" cannot have a "parent" and also have "autoconfigure". Try setting autoconfigure="false" for the service. - */ public function testAutoConfigureAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The service "child_service" cannot have a "parent" and also have "autoconfigure". Try setting autoconfigure="false" for the service.'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_autoconfigure_with_parent.xml'); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Attribute "autowire" on service "child_service" cannot be inherited from "defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly. - */ public function testDefaultsAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Attribute "autowire" on service "child_service" cannot be inherited from "defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly.'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_defaults_with_parent.xml'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php index d75efe47aa..2e6765210f 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php @@ -49,12 +49,10 @@ class YamlFileLoaderTest extends TestCase require_once self::$fixturesPath.'/includes/ProjectExtension.php'; } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /The file ".+" does not exist./ - */ public function testLoadUnExistFile() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The file ".+" does not exist./'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini')); $r = new \ReflectionObject($loader); $m = $r->getMethod('loadFile'); @@ -63,12 +61,10 @@ class YamlFileLoaderTest extends TestCase $m->invoke($loader, 'foo.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /The file ".+" does not contain valid YAML./ - */ public function testLoadInvalidYamlFile() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The file ".+" does not contain valid YAML./'); $path = self::$fixturesPath.'/ini'; $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator($path)); $r = new \ReflectionObject($loader); @@ -80,10 +76,10 @@ class YamlFileLoaderTest extends TestCase /** * @dataProvider provideInvalidFiles - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException */ public function testLoadInvalidFile($file) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); $loader->load($file.'.yml'); @@ -324,22 +320,18 @@ class YamlFileLoaderTest extends TestCase $this->assertEquals(['manager' => [['alias' => 'user']]], $definition->getTags()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /The tag name for service ".+" in .+ must be a non-empty string/ - */ public function testTagWithEmptyNameThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The tag name for service ".+" in .+ must be a non-empty string/'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('tag_name_empty_string.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageREgExp /The tag name for service "\.+" must be a non-empty string/ - */ public function testTagWithNonStringNameThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The tag name for service ".+" in .+ must be a non-empty string/'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('tag_name_no_string.yml'); } @@ -433,12 +425,10 @@ class YamlFileLoaderTest extends TestCase $this->assertFalse($container->getDefinition(Prototype\OtherDir\Component2\Dir2\Service5::class)->hasTag('foo')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /A "resource" attribute must be set when the "namespace" attribute is set for service ".+" in .+/ - */ public function testPrototypeWithNamespaceAndNoResource() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/A "resource" attribute must be set when the "namespace" attribute is set for service ".+" in .+/'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services_prototype_namespace_without_resource.yml'); @@ -509,78 +499,64 @@ class YamlFileLoaderTest extends TestCase $this->assertSame(['foo' => [[]], 'bar' => [[]]], $definition->getTags()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The service "child_service" cannot use the "parent" option in the same file where "_instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file. - */ public function testInstanceOfAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The service "child_service" cannot use the "parent" option in the same file where "_instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file.'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services_instanceof_with_parent.yml'); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The service "child_service" cannot have a "parent" and also have "autoconfigure". Try setting "autoconfigure: false" for the service. - */ public function testAutoConfigureAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The service "child_service" cannot have a "parent" and also have "autoconfigure". Try setting "autoconfigure: false" for the service.'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services_autoconfigure_with_parent.yml'); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Attribute "autowire" on service "child_service" cannot be inherited from "_defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly. - */ public function testDefaultsAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Attribute "autowire" on service "child_service" cannot be inherited from "_defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly.'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services_defaults_with_parent.yml'); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The value of the "parent" option for the "bar" service must be the id of the service without the "@" prefix (replace "@foo" with "foo"). - */ public function testChildDefinitionWithWrongSyntaxThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The value of the "parent" option for the "bar" service must be the id of the service without the "@" prefix (replace "@foo" with "foo").'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('bad_parent.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The value of the "decorates" option for the "bar" service must be the id of the service without the "@" prefix (replace "@foo" with "foo"). - */ public function testDecoratedServicesWithWrongSyntaxThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The value of the "decorates" option for the "bar" service must be the id of the service without the "@" prefix (replace "@foo" with "foo").'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('bad_decorates.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /Parameter "tags" must be an array for service "Foo\\Bar" in .+services31_invalid_tags\.yml\. Check your YAML syntax./ - */ public function testInvalidTagsWithDefaults() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Parameter "tags" must be an array for service "Foo\\\Bar" in .+services31_invalid_tags\.yml\. Check your YAML syntax./'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services31_invalid_tags.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Service names that start with an underscore are reserved. Rename the "_foo" service or define it in XML instead. - */ public function testUnderscoreServiceId() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Service names that start with an underscore are reserved. Rename the "_foo" service or define it in XML instead.'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services_underscore.yml'); @@ -659,23 +635,19 @@ class YamlFileLoaderTest extends TestCase $this->assertFalse($container->has('Bar')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /Creating an alias using the tag "!service" is not allowed in ".+anonymous_services_alias\.yml"\./ - */ public function testAnonymousServicesWithAliases() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Creating an alias using the tag "!service" is not allowed in ".+anonymous_services_alias\.yml"\./'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('anonymous_services_alias.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /Using an anonymous service in a parameter is not allowed in ".+anonymous_services_in_parameters\.yml"\./ - */ public function testAnonymousServicesInParameters() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Using an anonymous service in a parameter is not allowed in ".+anonymous_services_in_parameters\.yml"\./'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('anonymous_services_in_parameters.yml'); @@ -691,45 +663,37 @@ class YamlFileLoaderTest extends TestCase $this->assertFalse($container->getDefinition('override_defaults_settings_to_false')->isAutoconfigured()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /Service "_defaults" key must be an array, "NULL" given in ".+bad_empty_defaults\.yml"\./ - */ public function testEmptyDefaultsThrowsClearException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Service "_defaults" key must be an array, "NULL" given in ".+bad_empty_defaults\.yml"\./'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('bad_empty_defaults.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /Service "_instanceof" key must be an array, "NULL" given in ".+bad_empty_instanceof\.yml"\./ - */ public function testEmptyInstanceofThrowsClearException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Service "_instanceof" key must be an array, "NULL" given in ".+bad_empty_instanceof\.yml"\./'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('bad_empty_instanceof.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /^The configuration key "private" is unsupported for definition "bar"/ - */ public function testUnsupportedKeywordThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/^The configuration key "private" is unsupported for definition "bar"/'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('bad_keyword.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /^The configuration key "calls" is unsupported for the service "bar" which is defined as an alias/ - */ public function testUnsupportedKeywordInServiceAliasThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/^The configuration key "calls" is unsupported for the service "bar" which is defined as an alias/'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('bad_alias.yml'); @@ -784,12 +748,10 @@ class YamlFileLoaderTest extends TestCase ], array_map(function (BoundArgument $v) { return $v->getValues()[0]; }, $definition->getBindings())); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Cannot autowire service "Symfony\Component\DependencyInjection\Tests\Fixtures\ConstructNotExists": argument "$notExist" of method "__construct()" has type "Symfony\Component\DependencyInjection\Tests\Fixtures\NotExist" but this class was not found. - */ public function testProcessNotExistingActionParam() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Cannot autowire service "Symfony\Component\DependencyInjection\Tests\Fixtures\ConstructNotExists": argument "$notExist" of method "__construct()" has type "Symfony\Component\DependencyInjection\Tests\Fixtures\NotExist" but this class was not found.'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services_not_existing.yml'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/ContainerBagTest.php b/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/ContainerBagTest.php index c807b2c989..81be4fb74e 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/ContainerBagTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/ContainerBagTest.php @@ -48,11 +48,9 @@ class ContainerBagTest extends TestCase $this->assertSame('value', $this->containerBag->get('foo')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - */ public function testGetParameterNotFound() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $this->containerBag->get('bar'); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php b/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php index f83fce46d3..58f7a18dd9 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php @@ -19,11 +19,9 @@ class EnvPlaceholderParameterBagTest extends TestCase { use ForwardCompatTestTrait; - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - */ public function testGetThrowsInvalidArgumentExceptionIfEnvNameContainsNonWordCharacters() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $bag = new EnvPlaceholderParameterBag(); $bag->get('env(%foo%)'); } @@ -114,24 +112,22 @@ class EnvPlaceholderParameterBagTest extends TestCase $this->assertCount(2, $merged[$envName]); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The default value of env parameter "INT_VAR" must be a string or null, integer given. - */ public function testResolveEnvRequiresStrings() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The default value of env parameter "INT_VAR" must be a string or null, integer given.'); + $bag = new EnvPlaceholderParameterBag(); $bag->get('env(INT_VAR)'); $bag->set('env(INT_VAR)', 2); $bag->resolve(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The default value of an env() parameter must be a string or null, but "integer" given to "env(INT_VAR)". - */ public function testGetDefaultScalarEnv() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The default value of an env() parameter must be a string or null, but "integer" given to "env(INT_VAR)".'); + $bag = new EnvPlaceholderParameterBag(); $bag->set('env(INT_VAR)', 2); $bag->get('env(INT_VAR)'); @@ -158,12 +154,10 @@ class EnvPlaceholderParameterBagTest extends TestCase $this->assertNull($bag->all()['env(NULL_VAR)']); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The default value of env parameter "ARRAY_VAR" must be a string or null, array given. - */ public function testResolveThrowsOnBadDefaultValue() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The default value of env parameter "ARRAY_VAR" must be a string or null, array given.'); $bag = new EnvPlaceholderParameterBag(); $bag->get('env(ARRAY_VAR)'); $bag->set('env(ARRAY_VAR)', []); @@ -180,12 +174,10 @@ class EnvPlaceholderParameterBagTest extends TestCase $this->assertNull($bag->all()['env(NULL_VAR)']); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The default value of an env() parameter must be a string or null, but "array" given to "env(ARRAY_VAR)". - */ public function testGetThrowsOnBadDefaultValue() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The default value of an env() parameter must be a string or null, but "array" given to "env(ARRAY_VAR)".'); $bag = new EnvPlaceholderParameterBag(); $bag->set('env(ARRAY_VAR)', []); $bag->get('env(ARRAY_VAR)'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/FrozenParameterBagTest.php b/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/FrozenParameterBagTest.php index b168e0c20a..532a5a014f 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/FrozenParameterBagTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/FrozenParameterBagTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\DependencyInjection\Tests\ParameterBag; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; class FrozenParameterBagTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $parameters = [ @@ -26,38 +29,30 @@ class FrozenParameterBagTest extends TestCase $this->assertEquals($parameters, $bag->all(), '__construct() takes an array of parameters as its first argument'); } - /** - * @expectedException \LogicException - */ public function testClear() { + $this->expectException('LogicException'); $bag = new FrozenParameterBag([]); $bag->clear(); } - /** - * @expectedException \LogicException - */ public function testSet() { + $this->expectException('LogicException'); $bag = new FrozenParameterBag([]); $bag->set('foo', 'bar'); } - /** - * @expectedException \LogicException - */ public function testAdd() { + $this->expectException('LogicException'); $bag = new FrozenParameterBag([]); $bag->add([]); } - /** - * @expectedException \LogicException - */ public function testRemove() { + $this->expectException('LogicException'); $bag = new FrozenParameterBag(['foo' => 'bar']); $bag->remove('foo'); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php b/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php index 2d3092ae0d..5b56b96262 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\DependencyInjection\Tests; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\ServiceLocator; use Symfony\Contracts\Service\ServiceSubscriberInterface; @@ -18,17 +19,17 @@ use Symfony\Contracts\Service\Test\ServiceLocatorTest as BaseServiceLocatorTest; class ServiceLocatorTest extends BaseServiceLocatorTest { + use ForwardCompatTestTrait; + public function getServiceLocator(array $factories) { return new ServiceLocator($factories); } - /** - * @expectedException \Psr\Container\NotFoundExceptionInterface - * @expectedExceptionMessage 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. - */ public function testGetThrowsOnUndefinedService() { + $this->expectException('Psr\Container\NotFoundExceptionInterface'); + $this->expectExceptionMessage('Service "dummy" not found: the container inside "Symfony\Component\DependencyInjection\Tests\ServiceLocatorTest" is a smaller service locator that only knows about the "foo" and "bar" services.'); $locator = $this->getServiceLocator([ 'foo' => function () { return 'bar'; }, 'bar' => function () { return 'baz'; }, @@ -37,21 +38,17 @@ class ServiceLocatorTest extends BaseServiceLocatorTest $locator->get('dummy'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - * @expectedExceptionMessage Circular reference detected for service "bar", path: "bar -> baz -> bar". - */ public function testThrowsOnCircularReference() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); + $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> baz -> bar".'); parent::testThrowsOnCircularReference(); } - /** - * @expectedException \Psr\Container\NotFoundExceptionInterface - * @expectedExceptionMessage 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()". - */ public function testThrowsInServiceSubscriber() { + $this->expectException('Psr\Container\NotFoundExceptionInterface'); + $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(); @@ -61,12 +58,10 @@ class ServiceLocatorTest extends BaseServiceLocatorTest $subscriber->getFoo(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage 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. - */ public function testGetThrowsServiceNotFoundException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $this->expectExceptionMessage('Service "foo" not found: even though it exists in the app\'s container, the container inside "foo" is a smaller service locator that is empty... Try using dependency injection instead.'); $container = new Container(); $container->set('foo', new \stdClass()); diff --git a/src/Symfony/Component/DomCrawler/Tests/AbstractCrawlerTest.php b/src/Symfony/Component/DomCrawler/Tests/AbstractCrawlerTest.php index 1e5baf73c5..9a6f9579b0 100644 --- a/src/Symfony/Component/DomCrawler/Tests/AbstractCrawlerTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/AbstractCrawlerTest.php @@ -79,21 +79,17 @@ abstract class AbstractCrawlerTest extends TestCase $this->assertEquals('Foo', $crawler->filterXPath('//body')->text(), '->add() adds nodes from a string'); } - /** - * @expectedException \InvalidArgumentException - */ public function testAddInvalidType() { + $this->expectException('InvalidArgumentException'); $crawler = $this->createCrawler(); $crawler->add(1); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Attaching DOM nodes from multiple documents in the same crawler is forbidden. - */ public function testAddMultipleDocumentNode() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Attaching DOM nodes from multiple documents in the same crawler is forbidden.'); $crawler = $this->createTestCrawler(); $crawler->addHtmlContent($this->getDoctype().'
', 'UTF-8'); } @@ -725,22 +721,18 @@ HTML; } } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The selected node should be instance of DOMElement - */ public function testInvalidLink() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The selected node should be instance of DOMElement'); $crawler = $this->createTestCrawler('http://example.com/bar/'); $crawler->filterXPath('//li/text()')->link(); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The selected node should be instance of DOMElement - */ public function testInvalidLinks() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The selected node should be instance of DOMElement'); $crawler = $this->createTestCrawler('http://example.com/bar/'); $crawler->filterXPath('//li/text()')->link(); } @@ -841,12 +833,10 @@ HTML; } } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The selected node should be instance of DOMElement - */ public function testInvalidForm() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The selected node should be instance of DOMElement'); $crawler = $this->createTestCrawler('http://example.com/bar/'); $crawler->filterXPath('//li/text()')->form(); } @@ -954,7 +944,7 @@ HTML; $this->assertTrue(true, '->children() does not trigger a notice if the node has no children'); } catch (\PHPUnit\Framework\Error\Notice $e) { $this->fail('->children() does not trigger a notice if the node has no children'); - } catch (\PHPUnit_Framework_Error_Notice $e) { + } catch (\PHPUnit\Framework\Error\Notice $e) { $this->fail('->children() does not trigger a notice if the node has no children'); } } @@ -1095,11 +1085,9 @@ HTML; $this->assertSame('input', $crawler->first()->nodeName()); } - /** - * @expectedException \LogicException - */ public function testEvaluateThrowsAnExceptionIfDocumentIsEmpty() { + $this->expectException('LogicException'); $this->createCrawler()->evaluate('//form/input[1]'); } diff --git a/src/Symfony/Component/DomCrawler/Tests/FormTest.php b/src/Symfony/Component/DomCrawler/Tests/FormTest.php index d569eb203d..2d5a10ea01 100644 --- a/src/Symfony/Component/DomCrawler/Tests/FormTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/FormTest.php @@ -67,11 +67,10 @@ class FormTest extends TestCase /** * __construct() should throw \\LogicException if the form attribute is invalid. - * - * @expectedException \LogicException */ public function testConstructorThrowsExceptionIfNoRelatedForm() { + $this->expectException('LogicException'); $dom = new \DOMDocument(); $dom->loadHTML(' @@ -729,20 +728,16 @@ class FormTest extends TestCase $registry->remove('[t:dbt%3adate;]data_daterange_enddate_value'); } - /** - * @expectedException \InvalidArgumentException - */ public function testFormFieldRegistryGetThrowAnExceptionWhenTheFieldDoesNotExist() { + $this->expectException('InvalidArgumentException'); $registry = new FormFieldRegistry(); $registry->get('foo'); } - /** - * @expectedException \InvalidArgumentException - */ public function testFormFieldRegistrySetThrowAnExceptionWhenTheFieldDoesNotExist() { + $this->expectException('InvalidArgumentException'); $registry = new FormFieldRegistry(); $registry->set('foo', null); } @@ -819,24 +814,20 @@ class FormTest extends TestCase ]); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Cannot set value on a compound field "foo[bar]". - */ public function testFormRegistrySetValueOnCompoundField() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Cannot set value on a compound field "foo[bar]".'); $registry = new FormFieldRegistry(); $registry->add($this->getFormFieldMock('foo[bar][baz]')); $registry->set('foo[bar]', 'fbb'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Unreachable field "0" - */ public function testFormRegistrySetArrayOnNotCompoundField() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Unreachable field "0"'); $registry = new FormFieldRegistry(); $registry->add($this->getFormFieldMock('bar')); diff --git a/src/Symfony/Component/DomCrawler/Tests/ImageTest.php b/src/Symfony/Component/DomCrawler/Tests/ImageTest.php index 6aecadbc14..a3a0cfd2d7 100644 --- a/src/Symfony/Component/DomCrawler/Tests/ImageTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/ImageTest.php @@ -12,15 +12,16 @@ namespace Symfony\Component\DomCrawler\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DomCrawler\Image; class ImageTest extends TestCase { - /** - * @expectedException \LogicException - */ + use ForwardCompatTestTrait; + public function testConstructorWithANonImgTag() { + $this->expectException('LogicException'); $dom = new \DOMDocument(); $dom->loadHTML('
'); @@ -36,11 +37,9 @@ class ImageTest extends TestCase $this->assertSame('https://example.com/foo', $image->getUri()); } - /** - * @expectedException \InvalidArgumentException - */ public function testAbsoluteBaseUriIsMandatoryWhenImageUrlIsRelative() { + $this->expectException('InvalidArgumentException'); $dom = new \DOMDocument(); $dom->loadHTML('foo'); diff --git a/src/Symfony/Component/DomCrawler/Tests/LinkTest.php b/src/Symfony/Component/DomCrawler/Tests/LinkTest.php index 76805bb764..7874e6a438 100644 --- a/src/Symfony/Component/DomCrawler/Tests/LinkTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/LinkTest.php @@ -12,15 +12,16 @@ namespace Symfony\Component\DomCrawler\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DomCrawler\Link; class LinkTest extends TestCase { - /** - * @expectedException \LogicException - */ + use ForwardCompatTestTrait; + public function testConstructorWithANonATag() { + $this->expectException('LogicException'); $dom = new \DOMDocument(); $dom->loadHTML('
'); @@ -36,11 +37,9 @@ class LinkTest extends TestCase $this->assertSame('https://example.com/foo', $link->getUri()); } - /** - * @expectedException \InvalidArgumentException - */ public function testAbsoluteBaseUriIsMandatoryWhenLinkUrlIsRelative() { + $this->expectException('InvalidArgumentException'); $dom = new \DOMDocument(); $dom->loadHTML('foo'); diff --git a/src/Symfony/Component/Dotenv/Tests/DotenvTest.php b/src/Symfony/Component/Dotenv/Tests/DotenvTest.php index 208f6a99c2..f151973cec 100644 --- a/src/Symfony/Component/Dotenv/Tests/DotenvTest.php +++ b/src/Symfony/Component/Dotenv/Tests/DotenvTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Dotenv\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Dotenv\Dotenv; use Symfony\Component\Dotenv\Exception\FormatException; class DotenvTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getEnvDataWithFormatErrors */ @@ -305,11 +308,9 @@ class DotenvTest extends TestCase $this->assertSame('BAZ', $bar); } - /** - * @expectedException \Symfony\Component\Dotenv\Exception\PathException - */ public function testLoadDirectory() { + $this->expectException('Symfony\Component\Dotenv\Exception\PathException'); $dotenv = new Dotenv(true); $dotenv->load(__DIR__); } diff --git a/src/Symfony/Component/ErrorHandler/Tests/DebugClassLoaderTest.php b/src/Symfony/Component/ErrorHandler/Tests/DebugClassLoaderTest.php index 5944cf6fec..a0d92a680a 100644 --- a/src/Symfony/Component/ErrorHandler/Tests/DebugClassLoaderTest.php +++ b/src/Symfony/Component/ErrorHandler/Tests/DebugClassLoaderTest.php @@ -58,12 +58,10 @@ class DebugClassLoaderTest extends TestCase $this->fail('DebugClassLoader did not register'); } - /** - * @expectedException \Exception - * @expectedExceptionMessage boo - */ public function testThrowingClass() { + $this->expectException('Exception'); + $this->expectExceptionMessage('boo'); try { class_exists(__NAMESPACE__.'\Fixtures\Throwing'); $this->fail('Exception expected'); @@ -75,20 +73,16 @@ class DebugClassLoaderTest extends TestCase class_exists(__NAMESPACE__.'\Fixtures\Throwing'); } - /** - * @expectedException \RuntimeException - */ public function testNameCaseMismatch() { + $this->expectException('RuntimeException'); class_exists(__NAMESPACE__.'\TestingCaseMismatch', true); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Case mismatch between class and real file names - */ public function testFileCaseMismatch() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Case mismatch between class and real file names'); if (!file_exists(__DIR__.'/Fixtures/CaseMismatch.php')) { $this->markTestSkipped('Can only be run on case insensitive filesystems'); } @@ -96,11 +90,9 @@ class DebugClassLoaderTest extends TestCase class_exists(__NAMESPACE__.'\Fixtures\CaseMismatch', true); } - /** - * @expectedException \RuntimeException - */ public function testPsr4CaseMismatch() { + $this->expectException('RuntimeException'); class_exists(__NAMESPACE__.'\Fixtures\Psr4CaseMismatch', true); } diff --git a/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php b/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php index a23c96a785..fbece7707b 100644 --- a/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php +++ b/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php @@ -491,11 +491,9 @@ class ErrorHandlerTest extends TestCase $this->assertStringStartsWith("Attempted to load class \"IReallyReallyDoNotExistAnywhereInTheRepositoryISwear\" from the global namespace.\nDid you forget a \"use\" statement", $args[0]->getMessage()); } - /** - * @expectedException \Exception - */ public function testCustomExceptionHandler() { + $this->expectException('Exception'); $handler = new ErrorHandler(); $handler->setExceptionHandler(function ($e) use ($handler) { $handler->handleException($e); diff --git a/src/Symfony/Component/ErrorRenderer/Tests/Command/DebugCommandTest.php b/src/Symfony/Component/ErrorRenderer/Tests/Command/DebugCommandTest.php index 2a9174727d..383de253e1 100644 --- a/src/Symfony/Component/ErrorRenderer/Tests/Command/DebugCommandTest.php +++ b/src/Symfony/Component/ErrorRenderer/Tests/Command/DebugCommandTest.php @@ -78,12 +78,10 @@ TXT return new CommandTester($application->find('debug:error-renderer')); } - /** - * @expectedException \Symfony\Component\Console\Exception\InvalidArgumentException - * @expectedExceptionMessage No error renderer found for format "foo". Known format are json, xml, txt. - */ public function testInvalidFormat() { + $this->expectException('Symfony\Component\Console\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('No error renderer found for format "foo". Known format are json, xml, txt.'); $tester = $this->createCommandTester(); $tester->execute(['format' => 'foo'], ['decorated' => false]); } diff --git a/src/Symfony/Component/ErrorRenderer/Tests/DependencyInjection/LazyLoadingErrorRendererTest.php b/src/Symfony/Component/ErrorRenderer/Tests/DependencyInjection/LazyLoadingErrorRendererTest.php index 3ee8e5aca7..5811a0c026 100644 --- a/src/Symfony/Component/ErrorRenderer/Tests/DependencyInjection/LazyLoadingErrorRendererTest.php +++ b/src/Symfony/Component/ErrorRenderer/Tests/DependencyInjection/LazyLoadingErrorRendererTest.php @@ -19,12 +19,10 @@ use Symfony\Component\ErrorRenderer\Exception\FlattenException; class LazyLoadingErrorRendererTest extends TestCase { - /** - * @expectedException \Symfony\Component\ErrorRenderer\Exception\ErrorRendererNotFoundException - * @expectedExceptionMessage No error renderer found for format "foo". - */ public function testInvalidErrorRenderer() { + $this->expectException('Symfony\Component\ErrorRenderer\Exception\ErrorRendererNotFoundException'); + $this->expectExceptionMessage('No error renderer found for format "foo".'); $container = $this->getMockBuilder(ContainerInterface::class)->getMock(); $container->expects($this->once())->method('has')->with('foo')->willReturn(false); diff --git a/src/Symfony/Component/ErrorRenderer/Tests/ErrorRendererTest.php b/src/Symfony/Component/ErrorRenderer/Tests/ErrorRendererTest.php index 6664b6008b..11ef6a7d7e 100644 --- a/src/Symfony/Component/ErrorRenderer/Tests/ErrorRendererTest.php +++ b/src/Symfony/Component/ErrorRenderer/Tests/ErrorRendererTest.php @@ -18,21 +18,17 @@ use Symfony\Component\ErrorRenderer\Exception\FlattenException; class ErrorRendererTest extends TestCase { - /** - * @expectedException \Symfony\Component\ErrorRenderer\Exception\ErrorRendererNotFoundException - * @expectedExceptionMessage No error renderer found for format "foo". - */ public function testErrorRendererNotFound() { + $this->expectException('Symfony\Component\ErrorRenderer\Exception\ErrorRendererNotFoundException'); + $this->expectExceptionMessage('No error renderer found for format "foo".'); $exception = FlattenException::createFromThrowable(new \Exception('foo')); (new ErrorRenderer([]))->render($exception, 'foo'); } - /** - * @expectedException \TypeError - */ public function testInvalidErrorRenderer() { + $this->expectException('TypeError'); new ErrorRenderer([new \stdClass()]); } diff --git a/src/Symfony/Component/EventDispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php b/src/Symfony/Component/EventDispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php index d665f426e0..e56d49dc4b 100644 --- a/src/Symfony/Component/EventDispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php +++ b/src/Symfony/Component/EventDispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\EventDispatcher\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; @@ -19,14 +20,15 @@ use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass; class RegisterListenersPassTest extends TestCase { + use ForwardCompatTestTrait; + /** * Tests that event subscribers not implementing EventSubscriberInterface * trigger an exception. - * - * @expectedException \InvalidArgumentException */ public function testEventSubscriberWithoutInterface() { + $this->expectException('InvalidArgumentException'); $builder = new ContainerBuilder(); $builder->register('event_dispatcher'); $builder->register('my_event_subscriber', 'stdClass') @@ -63,12 +65,10 @@ class RegisterListenersPassTest extends TestCase $this->assertEquals($expectedCalls, $eventDispatcherDefinition->getMethodCalls()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The service "foo" tagged "kernel.event_listener" must not be abstract. - */ public function testAbstractEventListener() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The service "foo" tagged "kernel.event_listener" must not be abstract.'); $container = new ContainerBuilder(); $container->register('foo', 'stdClass')->setAbstract(true)->addTag('kernel.event_listener', []); $container->register('event_dispatcher', 'stdClass'); @@ -77,12 +77,10 @@ class RegisterListenersPassTest extends TestCase $registerListenersPass->process($container); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The service "foo" tagged "kernel.event_subscriber" must not be abstract. - */ public function testAbstractEventSubscriber() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The service "foo" tagged "kernel.event_subscriber" must not be abstract.'); $container = new ContainerBuilder(); $container->register('foo', 'stdClass')->setAbstract(true)->addTag('kernel.event_subscriber', []); $container->register('event_dispatcher', 'stdClass'); @@ -128,12 +126,10 @@ class RegisterListenersPassTest extends TestCase $this->assertTrue($container->getDefinition('foo')->hasTag('container.hot_path')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage You have requested a non-existent parameter "subscriber.class" - */ public function testEventSubscriberUnresolvableClassName() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('You have requested a non-existent parameter "subscriber.class"'); $container = new ContainerBuilder(); $container->register('foo', '%subscriber.class%')->addTag('kernel.event_subscriber', []); $container->register('event_dispatcher', 'stdClass'); diff --git a/src/Symfony/Component/EventDispatcher/Tests/GenericEventTest.php b/src/Symfony/Component/EventDispatcher/Tests/GenericEventTest.php index dfcd2431ec..fb9e1620a7 100644 --- a/src/Symfony/Component/EventDispatcher/Tests/GenericEventTest.php +++ b/src/Symfony/Component/EventDispatcher/Tests/GenericEventTest.php @@ -81,11 +81,9 @@ class GenericEventTest extends TestCase $this->assertEquals('Event', $this->event->getArgument('name')); } - /** - * @expectedException \InvalidArgumentException - */ public function testGetArgException() { + $this->expectException('\InvalidArgumentException'); $this->event->getArgument('nameNotExist'); } diff --git a/src/Symfony/Component/EventDispatcher/Tests/ImmutableEventDispatcherTest.php b/src/Symfony/Component/EventDispatcher/Tests/ImmutableEventDispatcherTest.php index 3b519dd45f..fc5b1228a8 100644 --- a/src/Symfony/Component/EventDispatcher/Tests/ImmutableEventDispatcherTest.php +++ b/src/Symfony/Component/EventDispatcher/Tests/ImmutableEventDispatcherTest.php @@ -73,37 +73,29 @@ class ImmutableEventDispatcherTest extends TestCase $this->assertSame('result', $this->dispatcher->hasListeners('event')); } - /** - * @expectedException \BadMethodCallException - */ public function testAddListenerDisallowed() { + $this->expectException('\BadMethodCallException'); $this->dispatcher->addListener('event', function () { return 'foo'; }); } - /** - * @expectedException \BadMethodCallException - */ public function testAddSubscriberDisallowed() { + $this->expectException('\BadMethodCallException'); $subscriber = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventSubscriberInterface')->getMock(); $this->dispatcher->addSubscriber($subscriber); } - /** - * @expectedException \BadMethodCallException - */ public function testRemoveListenerDisallowed() { + $this->expectException('\BadMethodCallException'); $this->dispatcher->removeListener('event', function () { return 'foo'; }); } - /** - * @expectedException \BadMethodCallException - */ public function testRemoveSubscriberDisallowed() { + $this->expectException('\BadMethodCallException'); $subscriber = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventSubscriberInterface')->getMock(); $this->dispatcher->removeSubscriber($subscriber); diff --git a/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionFunctionTest.php b/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionFunctionTest.php index f2710fb1e5..8d81c2b9d9 100644 --- a/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionFunctionTest.php +++ b/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionFunctionTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\ExpressionLanguage\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\ExpressionLanguage\ExpressionFunction; /** @@ -21,21 +22,19 @@ use Symfony\Component\ExpressionLanguage\ExpressionFunction; */ class ExpressionFunctionTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage PHP function "fn_does_not_exist" does not exist. - */ + use ForwardCompatTestTrait; + public function testFunctionDoesNotExist() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('PHP function "fn_does_not_exist" does not exist.'); ExpressionFunction::fromPhp('fn_does_not_exist'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage An expression function name must be defined when PHP function "Symfony\Component\ExpressionLanguage\Tests\fn_namespaced" is namespaced. - */ public function testFunctionNamespaced() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('An expression function name must be defined when PHP function "Symfony\Component\ExpressionLanguage\Tests\fn_namespaced" is namespaced.'); ExpressionFunction::fromPhp('Symfony\Component\ExpressionLanguage\Tests\fn_namespaced'); } } diff --git a/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php b/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php index 41a1f578d4..e19d7968fb 100644 --- a/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php +++ b/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\ExpressionLanguage\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\ExpressionLanguage\ExpressionFunction; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Symfony\Component\ExpressionLanguage\ParsedExpression; @@ -19,6 +20,8 @@ use Symfony\Component\ExpressionLanguage\Tests\Fixtures\TestProvider; class ExpressionLanguageTest extends TestCase { + use ForwardCompatTestTrait; + public function testCachedParse() { $cacheMock = $this->getMockBuilder('Psr\Cache\CacheItemPoolInterface')->getMock(); @@ -105,12 +108,10 @@ class ExpressionLanguageTest extends TestCase $this->assertSame($expected, $result); } - /** - * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError - * @expectedExceptionMessage Unexpected end of expression around position 6 for expression `node.`. - */ public function testParseThrowsInsteadOfNotice() { + $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError'); + $this->expectExceptionMessage('Unexpected end of expression around position 6 for expression `node.`.'); $expressionLanguage = new ExpressionLanguage(); $expressionLanguage->parse('node.', ['node']); } @@ -199,10 +200,10 @@ class ExpressionLanguageTest extends TestCase /** * @dataProvider getRegisterCallbacks - * @expectedException \LogicException */ public function testRegisterAfterParse($registerCallback) { + $this->expectException('LogicException'); $el = new ExpressionLanguage(); $el->parse('1 + 1', []); $registerCallback($el); @@ -210,31 +211,29 @@ class ExpressionLanguageTest extends TestCase /** * @dataProvider getRegisterCallbacks - * @expectedException \LogicException */ public function testRegisterAfterEval($registerCallback) { + $this->expectException('LogicException'); $el = new ExpressionLanguage(); $el->evaluate('1 + 1'); $registerCallback($el); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessageRegExp /Unable to call method "\w+" of object "\w+"./ - */ public function testCallBadCallable() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessageRegExp('/Unable to call method "\w+" of object "\w+"./'); $el = new ExpressionLanguage(); $el->evaluate('foo.myfunction()', ['foo' => new \stdClass()]); } /** * @dataProvider getRegisterCallbacks - * @expectedException \LogicException */ public function testRegisterAfterCompile($registerCallback) { + $this->expectException('LogicException'); $el = new ExpressionLanguage(); $el->compile('1 + 1'); $registerCallback($el); diff --git a/src/Symfony/Component/ExpressionLanguage/Tests/LexerTest.php b/src/Symfony/Component/ExpressionLanguage/Tests/LexerTest.php index d94dd74f06..b26f925cf0 100644 --- a/src/Symfony/Component/ExpressionLanguage/Tests/LexerTest.php +++ b/src/Symfony/Component/ExpressionLanguage/Tests/LexerTest.php @@ -40,22 +40,18 @@ class LexerTest extends TestCase $this->assertEquals(new TokenStream($tokens, $expression), $this->lexer->tokenize($expression)); } - /** - * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError - * @expectedExceptionMessage Unexpected character "'" around position 33 for expression `service(faulty.expression.example').dummyMethod()`. - */ public function testTokenizeThrowsErrorWithMessage() { + $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError'); + $this->expectExceptionMessage('Unexpected character "\'" around position 33 for expression `service(faulty.expression.example\').dummyMethod()`.'); $expression = "service(faulty.expression.example').dummyMethod()"; $this->lexer->tokenize($expression); } - /** - * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError - * @expectedExceptionMessage Unclosed "(" around position 7 for expression `service(unclosed.expression.dummyMethod()`. - */ public function testTokenizeThrowsErrorOnUnclosedBrace() { + $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError'); + $this->expectExceptionMessage('Unclosed "(" around position 7 for expression `service(unclosed.expression.dummyMethod()`.'); $expression = 'service(unclosed.expression.dummyMethod()'; $this->lexer->tokenize($expression); } diff --git a/src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php b/src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php index d030600fe8..8fcddeb606 100644 --- a/src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php +++ b/src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php @@ -12,29 +12,28 @@ namespace Symfony\Component\ExpressionLanguage\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\ExpressionLanguage\Lexer; use Symfony\Component\ExpressionLanguage\Node; use Symfony\Component\ExpressionLanguage\Parser; class ParserTest extends TestCase { - /** - * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError - * @expectedExceptionMessage Variable "foo" is not valid around position 1 for expression `foo`. - */ + use ForwardCompatTestTrait; + public function testParseWithInvalidName() { + $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError'); + $this->expectExceptionMessage('Variable "foo" is not valid around position 1 for expression `foo`.'); $lexer = new Lexer(); $parser = new Parser([]); $parser->parse($lexer->tokenize('foo')); } - /** - * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError - * @expectedExceptionMessage Variable "foo" is not valid around position 1 for expression `foo`. - */ public function testParseWithZeroInNames() { + $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError'); + $this->expectExceptionMessage('Variable "foo" is not valid around position 1 for expression `foo`.'); $lexer = new Lexer(); $parser = new Parser([]); $parser->parse($lexer->tokenize('foo'), [0]); @@ -165,10 +164,10 @@ class ParserTest extends TestCase /** * @dataProvider getInvalidPostfixData - * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError */ public function testParseWithInvalidPostfixData($expr, $names = []) { + $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError'); $lexer = new Lexer(); $parser = new Parser([]); $parser->parse($lexer->tokenize($expr), $names); @@ -196,12 +195,10 @@ class ParserTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError - * @expectedExceptionMessage Did you mean "baz"? - */ public function testNameProposal() { + $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError'); + $this->expectExceptionMessage('Did you mean "baz"?'); $lexer = new Lexer(); $parser = new Parser([]); diff --git a/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php b/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php index 320644fa00..05723f2836 100644 --- a/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php +++ b/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php @@ -11,11 +11,15 @@ namespace Symfony\Component\Filesystem\Tests; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; + /** * Test class for Filesystem. */ class FilesystemTest extends FilesystemTestCase { + use ForwardCompatTestTrait; + public function testCopyCreatesNewFile() { $sourceFilePath = $this->workspace.\DIRECTORY_SEPARATOR.'copy_source_file'; @@ -29,22 +33,18 @@ class FilesystemTest extends FilesystemTestCase $this->assertStringEqualsFile($targetFilePath, 'SOURCE FILE'); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testCopyFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $sourceFilePath = $this->workspace.\DIRECTORY_SEPARATOR.'copy_source_file'; $targetFilePath = $this->workspace.\DIRECTORY_SEPARATOR.'copy_target_file'; $this->filesystem->copy($sourceFilePath, $targetFilePath); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testCopyUnreadableFileFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); // skip test on Windows; PHP can't easily set file as unreadable on Windows if ('\\' === \DIRECTORY_SEPARATOR) { $this->markTestSkipped('This test cannot run on Windows.'); @@ -118,11 +118,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertStringEqualsFile($targetFilePath, 'SOURCE FILE'); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testCopyWithOverrideWithReadOnlyTargetFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); // skip test on Windows; PHP can't easily set file as unwritable on Windows if ('\\' === \DIRECTORY_SEPARATOR) { $this->markTestSkipped('This test cannot run on Windows.'); @@ -222,11 +220,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertTrue(is_dir($basePath.'3')); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testMkdirCreatesDirectoriesFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $basePath = $this->workspace.\DIRECTORY_SEPARATOR; $dir = $basePath.'2'; @@ -244,11 +240,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertFileExists($file); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testTouchFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $file = $this->workspace.\DIRECTORY_SEPARATOR.'1'.\DIRECTORY_SEPARATOR.'2'; $this->filesystem->touch($file); @@ -380,11 +374,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertTrue($this->filesystem->exists($basePath.'folder')); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testFilesExistsFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); if ('\\' !== \DIRECTORY_SEPARATOR) { $this->markTestSkipped('Long file names are an issue on Windows'); } @@ -595,11 +587,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertSame($owner, $this->getFileOwner($link)); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testChownSymlinkFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $this->markAsSkippedIfSymlinkIsMissing(); $file = $this->workspace.\DIRECTORY_SEPARATOR.'file'; @@ -612,11 +602,9 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->chown($link, 'user'.time().mt_rand(1000, 9999)); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testChownLinkFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $this->markAsSkippedIfLinkIsMissing(); $file = $this->workspace.\DIRECTORY_SEPARATOR.'file'; @@ -629,11 +617,9 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->chown($link, 'user'.time().mt_rand(1000, 9999)); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testChownFail() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $this->markAsSkippedIfPosixIsMissing(); $dir = $this->workspace.\DIRECTORY_SEPARATOR.'dir'; @@ -704,11 +690,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertSame($group, $this->getFileGroup($link)); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testChgrpSymlinkFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $this->markAsSkippedIfSymlinkIsMissing(); $file = $this->workspace.\DIRECTORY_SEPARATOR.'file'; @@ -721,11 +705,9 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->chgrp($link, 'user'.time().mt_rand(1000, 9999)); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testChgrpLinkFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $this->markAsSkippedIfLinkIsMissing(); $file = $this->workspace.\DIRECTORY_SEPARATOR.'file'; @@ -738,11 +720,9 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->chgrp($link, 'user'.time().mt_rand(1000, 9999)); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testChgrpFail() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $this->markAsSkippedIfPosixIsMissing(); $dir = $this->workspace.\DIRECTORY_SEPARATOR.'dir'; @@ -763,11 +743,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertFileExists($newPath); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testRenameThrowsExceptionIfTargetAlreadyExists() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $file = $this->workspace.\DIRECTORY_SEPARATOR.'file'; $newPath = $this->workspace.\DIRECTORY_SEPARATOR.'new_file'; @@ -791,11 +769,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertFileExists($newPath); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testRenameThrowsExceptionOnError() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $file = $this->workspace.\DIRECTORY_SEPARATOR.uniqid('fs_test_', true); $newPath = $this->workspace.\DIRECTORY_SEPARATOR.'new_file'; @@ -1134,21 +1110,17 @@ class FilesystemTest extends FilesystemTestCase return $paths; } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\InvalidArgumentException - * @expectedExceptionMessage The start path "var/lib/symfony/src/Symfony/Component" is not absolute. - */ public function testMakePathRelativeWithRelativeStartPath() { + $this->expectException('Symfony\Component\Filesystem\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The start path "var/lib/symfony/src/Symfony/Component" is not absolute.'); $this->assertSame('../../../', $this->filesystem->makePathRelative('/var/lib/symfony/', 'var/lib/symfony/src/Symfony/Component')); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\InvalidArgumentException - * @expectedExceptionMessage The end path "var/lib/symfony/" is not absolute. - */ public function testMakePathRelativeWithRelativeEndPath() { + $this->expectException('Symfony\Component\Filesystem\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The end path "var/lib/symfony/" is not absolute.'); $this->assertSame('../../../', $this->filesystem->makePathRelative('var/lib/symfony/', '/var/lib/symfony/src/Symfony/Component')); } @@ -1419,11 +1391,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertFileExists($filename); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testTempnamWithZlibSchemeFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $scheme = 'compress.zlib://'; $dirname = $scheme.$this->workspace; @@ -1444,11 +1414,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertFileNotExists($filename); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testTempnamWithPharSchemeFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); // Skip test if Phar disabled phar.readonly must be 0 in php.ini if (!\Phar::canWrite()) { $this->markTestSkipped('This test cannot run when phar.readonly is 1.'); @@ -1463,11 +1431,9 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->tempnam($dirname, $pharname.'/bar'); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testTempnamWithHTTPSchemeFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $scheme = 'http://'; $dirname = $scheme.$this->workspace; diff --git a/src/Symfony/Component/Finder/Tests/FinderTest.php b/src/Symfony/Component/Finder/Tests/FinderTest.php index d4a1cb306d..6fb77d6bef 100644 --- a/src/Symfony/Component/Finder/Tests/FinderTest.php +++ b/src/Symfony/Component/Finder/Tests/FinderTest.php @@ -11,10 +11,13 @@ namespace Symfony\Component\Finder\Tests; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Finder\Finder; class FinderTest extends Iterator\RealIteratorTestCase { + use ForwardCompatTestTrait; + public function testCreate() { $this->assertInstanceOf('Symfony\Component\Finder\Finder', Finder::create()); @@ -887,20 +890,16 @@ class FinderTest extends Iterator\RealIteratorTestCase $this->assertIterator($expected, $iterator); } - /** - * @expectedException \Symfony\Component\Finder\Exception\DirectoryNotFoundException - */ public function testInWithNonExistentDirectory() { + $this->expectException('Symfony\Component\Finder\Exception\DirectoryNotFoundException'); $finder = new Finder(); $finder->in('foobar'); } - /** - * @expectedException \InvalidArgumentException - */ public function testInWithNonExistentDirectoryLegacyException() { + $this->expectException('InvalidArgumentException'); $finder = new Finder(); $finder->in('foobar'); } @@ -913,11 +912,9 @@ class FinderTest extends Iterator\RealIteratorTestCase $this->assertIterator($this->toAbsoluteFixtures(['A/B/C/abc.dat', 'copy/A/B/C/abc.dat.copy']), $finder); } - /** - * @expectedException \InvalidArgumentException - */ public function testInWithNonDirectoryGlob() { + $this->expectException('InvalidArgumentException'); $finder = new Finder(); $finder->in(__DIR__.'/Fixtures/A/a*'); } @@ -934,11 +931,9 @@ class FinderTest extends Iterator\RealIteratorTestCase $this->assertIterator($this->toAbsoluteFixtures(['A/B/C/abc.dat', 'copy/A/B/C/abc.dat.copy']), $finder); } - /** - * @expectedException \LogicException - */ public function testGetIteratorWithoutIn() { + $this->expectException('LogicException'); $finder = Finder::create(); $finder->getIterator(); } @@ -1116,11 +1111,9 @@ class FinderTest extends Iterator\RealIteratorTestCase $this->assertCount($i, $files); } - /** - * @expectedException \LogicException - */ public function testCountWithoutIn() { + $this->expectException('LogicException'); $finder = Finder::create()->files(); \count($finder); } @@ -1374,7 +1367,7 @@ class FinderTest extends Iterator\RealIteratorTestCase $this->fail('Finder should throw an exception when opening a non-readable directory.'); } catch (\Exception $e) { $expectedExceptionClass = 'Symfony\\Component\\Finder\\Exception\\AccessDeniedException'; - if ($e instanceof \PHPUnit_Framework_ExpectationFailedException) { + if ($e instanceof \PHPUnit\Framework\ExpectationFailedException) { $this->fail(sprintf("Expected exception:\n%s\nGot:\n%s\nWith comparison failure:\n%s", $expectedExceptionClass, 'PHPUnit_Framework_ExpectationFailedException', $e->getComparisonFailure()->getExpectedAsString())); } diff --git a/src/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.php b/src/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.php index ad0187e032..9c6e7db03f 100644 --- a/src/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.php +++ b/src/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.php @@ -11,15 +11,16 @@ namespace Symfony\Component\Finder\Tests\Iterator; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Finder\Iterator\CustomFilterIterator; class CustomFilterIteratorTest extends IteratorTestCase { - /** - * @expectedException \InvalidArgumentException - */ + use ForwardCompatTestTrait; + public function testWithInvalidFilter() { + $this->expectException('InvalidArgumentException'); new CustomFilterIterator(new Iterator(), ['foo']); } diff --git a/src/Symfony/Component/Form/Tests/ButtonBuilderTest.php b/src/Symfony/Component/Form/Tests/ButtonBuilderTest.php index b3a56d63b9..4052c7c3dd 100644 --- a/src/Symfony/Component/Form/Tests/ButtonBuilderTest.php +++ b/src/Symfony/Component/Form/Tests/ButtonBuilderTest.php @@ -42,12 +42,11 @@ class ButtonBuilderTest extends TestCase $this->assertInstanceOf('\Symfony\Component\Form\ButtonBuilder', new ButtonBuilder($name)); } - /** - * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException - * @expectedExceptionMessage The name "button[]" contains illegal characters. Names should start with a letter, digit or underscore and only contain letters, digits, numbers, underscores ("_"), hyphens ("-") and colons (":"). - */ public function testNameContainingIllegalCharacters() { + $this->expectException('Symfony\Component\Form\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The name "button[]" contains illegal characters. Names should start with a letter, digit or underscore and only contain letters, digits, numbers, underscores ("_"), hyphens ("-") and colons (":").'); + $this->assertInstanceOf('\Symfony\Component\Form\ButtonBuilder', new ButtonBuilder('button[]')); } diff --git a/src/Symfony/Component/Form/Tests/ButtonTest.php b/src/Symfony/Component/Form/Tests/ButtonTest.php index 7f4344fe63..9243006995 100644 --- a/src/Symfony/Component/Form/Tests/ButtonTest.php +++ b/src/Symfony/Component/Form/Tests/ButtonTest.php @@ -33,11 +33,9 @@ class ButtonTest extends TestCase $this->factory = $this->getMockBuilder('Symfony\Component\Form\FormFactoryInterface')->getMock(); } - /** - * @expectedException \Symfony\Component\Form\Exception\AlreadySubmittedException - */ public function testSetParentOnSubmittedButton() { + $this->expectException('Symfony\Component\Form\Exception\AlreadySubmittedException'); $button = $this->getButtonBuilder('button') ->getForm() ; diff --git a/src/Symfony/Component/Form/Tests/Command/DebugCommandTest.php b/src/Symfony/Component/Form/Tests/Command/DebugCommandTest.php index ab4b0c1a46..acd7e969f1 100644 --- a/src/Symfony/Component/Form/Tests/Command/DebugCommandTest.php +++ b/src/Symfony/Component/Form/Tests/Command/DebugCommandTest.php @@ -82,12 +82,10 @@ TXT $this->assertContains('Symfony\Component\Form\Extension\Core\Type\FormType (method)', $tester->getDisplay()); } - /** - * @expectedException \Symfony\Component\Console\Exception\InvalidArgumentException - * @expectedExceptionMessage Could not find type "NonExistentType" - */ public function testDebugSingleFormTypeNotFound() { + $this->expectException('Symfony\Component\Console\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Could not find type "NonExistentType"'); $tester = $this->createCommandTester(); $tester->execute(['class' => 'NonExistentType'], ['decorated' => false, 'interactive' => false]); } @@ -139,11 +137,9 @@ TXT , $output); } - /** - * @expectedException \InvalidArgumentException - */ public function testDebugInvalidFormType() { + $this->expectException('InvalidArgumentException'); $this->createCommandTester()->execute(['class' => 'test']); } diff --git a/src/Symfony/Component/Form/Tests/CompoundFormTest.php b/src/Symfony/Component/Form/Tests/CompoundFormTest.php index 2fb535ae7e..de108e7dba 100644 --- a/src/Symfony/Component/Form/Tests/CompoundFormTest.php +++ b/src/Symfony/Component/Form/Tests/CompoundFormTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Tests; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper; use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler; @@ -26,6 +27,8 @@ use Symfony\Component\HttpFoundation\Request; class CompoundFormTest extends AbstractFormTest { + use ForwardCompatTestTrait; + public function testValidIfAllChildrenAreValid() { $this->form->add($this->getBuilder('firstName')->getForm()); @@ -269,11 +272,9 @@ class CompoundFormTest extends AbstractFormTest $this->assertSame(['foo' => $child], $this->form->all()); } - /** - * @expectedException \Symfony\Component\Form\Exception\AlreadySubmittedException - */ public function testAddThrowsExceptionIfAlreadySubmitted() { + $this->expectException('Symfony\Component\Form\Exception\AlreadySubmittedException'); $this->form->submit([]); $this->form->add($this->getBuilder('foo')->getForm()); } @@ -288,11 +289,9 @@ class CompoundFormTest extends AbstractFormTest $this->assertCount(0, $this->form); } - /** - * @expectedException \Symfony\Component\Form\Exception\AlreadySubmittedException - */ public function testRemoveThrowsExceptionIfAlreadySubmitted() { + $this->expectException('Symfony\Component\Form\Exception\AlreadySubmittedException'); $this->form->add($this->getBuilder('foo')->setCompound(false)->getForm()); $this->form->submit(['foo' => 'bar']); $this->form->remove('foo'); diff --git a/src/Symfony/Component/Form/Tests/DependencyInjection/FormPassTest.php b/src/Symfony/Component/Form/Tests/DependencyInjection/FormPassTest.php index b494bb3b17..cc2e9efded 100644 --- a/src/Symfony/Component/Form/Tests/DependencyInjection/FormPassTest.php +++ b/src/Symfony/Component/Form/Tests/DependencyInjection/FormPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -28,6 +29,8 @@ use Symfony\Component\Form\FormRegistry; */ class FormPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testDoNothingIfFormExtensionNotLoaded() { $container = $this->createContainerBuilder(); @@ -218,12 +221,10 @@ class FormPassTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The getExtendedTypes() method for service "my.type_extension" does not return any extended types. - */ public function testAddTaggedFormTypeExtensionWithoutExtendingAnyType() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The getExtendedTypes() method for service "my.type_extension" does not return any extended types.'); $container = $this->createContainerBuilder(); $container->setDefinition('form.extension', $this->createExtensionDefinition()); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.php index 09b81fc5e1..e1e7ad0eee 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.php @@ -71,11 +71,9 @@ class ArrayToPartsTransformerTest extends TestCase $this->assertSame($output, $this->transformer->transform(null)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testTransformRequiresArray() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $this->transformer->transform('12345'); } @@ -126,11 +124,9 @@ class ArrayToPartsTransformerTest extends TestCase $this->assertNull($this->transformer->reverseTransform($input)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformPartiallyNull() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $input = [ 'first' => [ 'a' => '1', @@ -143,11 +139,9 @@ class ArrayToPartsTransformerTest extends TestCase $this->transformer->reverseTransform($input); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformRequiresArray() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $this->transformer->reverseTransform('12345'); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTest.php index 283dd4a81d..d3dc7e3a26 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTest.php @@ -12,24 +12,23 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; class BaseDateTimeTransformerTest extends TestCase { - /** - * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException - * @expectedExceptionMessage this_timezone_does_not_exist - */ + use ForwardCompatTestTrait; + public function testConstructFailsIfInputTimezoneIsInvalid() { + $this->expectException('Symfony\Component\Form\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('this_timezone_does_not_exist'); $this->getMockBuilder('Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer')->setConstructorArgs(['this_timezone_does_not_exist'])->getMock(); } - /** - * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException - * @expectedExceptionMessage that_timezone_does_not_exist - */ public function testConstructFailsIfOutputTimezoneIsInvalid() { + $this->expectException('Symfony\Component\Form\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('that_timezone_does_not_exist'); $this->getMockBuilder('Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer')->setConstructorArgs([null, 'that_timezone_does_not_exist'])->getMock(); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.php index 54c7fe1293..a42a9525f9 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.php @@ -48,19 +48,15 @@ class BooleanToStringTransformerTest extends TestCase $this->assertNull($this->transformer->transform(null)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testTransformFailsIfString() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $this->transformer->transform('1'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformFailsIfInteger() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $this->transformer->reverseTransform(1); } @@ -80,11 +76,9 @@ class BooleanToStringTransformerTest extends TestCase $this->assertFalse($customFalseTransformer->reverseTransform(true)); } - /** - * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException - */ public function testTrueValueContainedInFalseValues() { + $this->expectException('Symfony\Component\Form\Exception\InvalidArgumentException'); new BooleanToStringTransformer('0', [null, '0']); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php index 37d383490f..ee007b40d1 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php @@ -91,10 +91,10 @@ class ChoiceToValueTransformerTest extends TestCase /** * @dataProvider reverseTransformExpectsStringOrNullProvider - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException */ public function testReverseTransformExpectsStringOrNull($value) { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $this->transformer->reverseTransform($value); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php index e741a3e11f..6f008ba187 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php @@ -56,11 +56,9 @@ class ChoicesToValuesTransformerTest extends TestCase $this->assertSame([], $this->transformer->transform(null)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testTransformExpectsArray() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $this->transformer->transform('foobar'); } @@ -84,11 +82,9 @@ class ChoicesToValuesTransformerTest extends TestCase $this->assertSame([], $this->transformerWithNull->reverseTransform(null)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformExpectsArray() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $this->transformer->reverseTransform('foobar'); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformerTest.php index 244ef0f790..9313e4f178 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformerTest.php @@ -35,12 +35,10 @@ class DateTimeImmutableToDateTimeTransformerTest extends TestCase $this->assertNull($transformer->transform(null)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage Expected a \DateTimeImmutable. - */ public function testTransformFail() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('Expected a \DateTimeImmutable.'); $transformer = new DateTimeImmutableToDateTimeTransformer(); $transformer->transform(new \DateTime()); } @@ -64,12 +62,10 @@ class DateTimeImmutableToDateTimeTransformerTest extends TestCase $this->assertNull($transformer->reverseTransform(null)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage Expected a \DateTime. - */ public function testReverseTransformFail() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('Expected a \DateTime.'); $transformer = new DateTimeImmutableToDateTimeTransformer(); $transformer->reverseTransform(new \DateTimeImmutable()); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.php index 2669d3d4af..5460203fc6 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToArrayTransformer; class DateTimeToArrayTransformerTest extends TestCase { + use ForwardCompatTestTrait; + public function testTransform() { $transformer = new DateTimeToArrayTransformer('UTC', 'UTC'); @@ -137,11 +140,9 @@ class DateTimeToArrayTransformerTest extends TestCase $this->assertSame($output, $transformer->transform($input)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testTransformRequiresDateTime() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform('12345'); } @@ -211,11 +212,9 @@ class DateTimeToArrayTransformerTest extends TestCase $this->assertNull($transformer->reverseTransform($input)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformPartiallyEmptyYear() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'month' => '2', @@ -226,11 +225,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformPartiallyEmptyMonth() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -241,11 +238,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformPartiallyEmptyDay() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -256,11 +251,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformPartiallyEmptyHour() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -271,11 +264,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformPartiallyEmptyMinute() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -286,11 +277,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformPartiallyEmptySecond() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -346,20 +335,16 @@ class DateTimeToArrayTransformerTest extends TestCase $this->assertEquals($output, $transformer->reverseTransform($input)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformRequiresArray() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform('12345'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithNegativeYear() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '-1', @@ -371,11 +356,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithNegativeMonth() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -387,11 +370,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithNegativeDay() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -403,11 +384,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithNegativeHour() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -419,11 +398,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithNegativeMinute() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -435,11 +412,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithNegativeSecond() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -451,11 +426,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithInvalidMonth() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -467,11 +440,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithInvalidDay() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -483,11 +454,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithStringDay() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -499,11 +468,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithStringMonth() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -515,11 +482,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithStringYear() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => 'bazinga', @@ -531,11 +496,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithEmptyStringHour() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -547,11 +510,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithEmptyStringMinute() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', @@ -563,11 +524,9 @@ class DateTimeToArrayTransformerTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithEmptyStringSecond() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToArrayTransformer(); $transformer->reverseTransform([ 'year' => '2010', diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php index 0db210a3c1..776009938d 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php @@ -12,11 +12,13 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToHtml5LocalDateTimeTransformer; use Symfony\Component\Form\Tests\Extension\Core\DataTransformer\Traits\DateTimeEqualsTrait; class DateTimeToHtml5LocalDateTimeTransformerTest extends TestCase { + use ForwardCompatTestTrait; use DateTimeEqualsTrait; public function transformProvider() @@ -71,11 +73,9 @@ class DateTimeToHtml5LocalDateTimeTransformerTest extends TestCase $this->assertSame($to, $transformer->transform(null !== $from ? new \DateTimeImmutable($from) : null)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testTransformRequiresValidDateTime() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToHtml5LocalDateTimeTransformer(); $transformer->transform('2010-01-01'); } @@ -94,30 +94,24 @@ class DateTimeToHtml5LocalDateTimeTransformerTest extends TestCase } } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformRequiresString() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToHtml5LocalDateTimeTransformer(); $transformer->reverseTransform(12345); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithNonExistingDate() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToHtml5LocalDateTimeTransformer('UTC', 'UTC'); $transformer->reverseTransform('2010-04-31T04:05'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformExpectsValidDateString() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToHtml5LocalDateTimeTransformer('UTC', 'UTC'); $transformer->reverseTransform('2010-2010-2010'); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php index 0248e9809d..b1287bbbca 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php @@ -175,11 +175,9 @@ class DateTimeToLocalizedStringTransformerTest extends TestCase $this->assertEquals($dateTime->format('d.m.Y, H:i'), $transformer->transform($input)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testTransformRequiresValidDateTime() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToLocalizedStringTransformer(); $transformer->transform('2010-01-01'); } @@ -285,57 +283,45 @@ class DateTimeToLocalizedStringTransformerTest extends TestCase $this->assertNull($transformer->reverseTransform('')); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformRequiresString() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToLocalizedStringTransformer(); $transformer->reverseTransform(12345); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWrapsIntlErrors() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToLocalizedStringTransformer(); $transformer->reverseTransform('12345'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithNonExistingDate() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC', \IntlDateFormatter::SHORT); $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('31.04.10 04:05')); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformOutOfTimestampRange() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC'); $transformer->reverseTransform('1789-07-14'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformFiveDigitYears() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC', null, null, \IntlDateFormatter::GREGORIAN, 'yyyy-MM-dd'); $transformer->reverseTransform('20107-03-21'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformFiveDigitYearsWithTimestamp() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC', null, null, \IntlDateFormatter::GREGORIAN, 'yyyy-MM-dd HH:mm:ss'); $transformer->reverseTransform('20107-03-21 12:34:56'); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php index ec251d8f35..3a2d9ab8bb 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php @@ -87,11 +87,9 @@ class DateTimeToRfc3339TransformerTest extends TestCase $this->assertSame($to, $transformer->transform(null !== $from ? new \DateTimeImmutable($from) : null)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testTransformRequiresValidDateTime() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToRfc3339Transformer(); $transformer->transform('2010-01-01'); } @@ -110,20 +108,16 @@ class DateTimeToRfc3339TransformerTest extends TestCase } } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformRequiresString() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToRfc3339Transformer(); $transformer->reverseTransform(12345); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformWithNonExistingDate() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToRfc3339Transformer('UTC', 'UTC'); $transformer->reverseTransform('2010-04-31T04:05Z'); @@ -131,10 +125,10 @@ class DateTimeToRfc3339TransformerTest extends TestCase /** * @dataProvider invalidDateStringProvider - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException */ public function testReverseTransformExpectsValidDateString($date) { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new DateTimeToRfc3339Transformer('UTC', 'UTC'); $transformer->reverseTransform($date); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeZoneToStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeZoneToStringTransformerTest.php index 6aefe3cab5..6bc0cd9a54 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeZoneToStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeZoneToStringTransformerTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeZoneToStringTransformer; class DateTimeZoneToStringTransformerTest extends TestCase { + use ForwardCompatTestTrait; + public function testSingle() { $transformer = new DateTimeZoneToStringTransformer(); @@ -38,19 +41,15 @@ class DateTimeZoneToStringTransformerTest extends TestCase $this->assertEquals([new \DateTimeZone('Europe/Amsterdam')], $transformer->reverseTransform(['Europe/Amsterdam'])); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testInvalidTimezone() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); (new DateTimeZoneToStringTransformer())->transform(1); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testUnknownTimezone() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); (new DateTimeZoneToStringTransformer(true))->reverseTransform(['Foo/Bar']); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php index e84657451b..427ca9b208 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php @@ -190,21 +190,17 @@ class IntegerToLocalizedStringTransformerTest extends TestCase $this->assertEquals($output, $transformer->reverseTransform($input)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformExpectsString() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new IntegerToLocalizedStringTransformer(); $transformer->reverseTransform(1); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformExpectsValidNumber() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new IntegerToLocalizedStringTransformer(); $transformer->reverseTransform('foo'); @@ -212,10 +208,10 @@ class IntegerToLocalizedStringTransformerTest extends TestCase /** * @dataProvider floatNumberProvider - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException */ public function testReverseTransformExpectsInteger($number, $locale) { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); IntlTestHelper::requireFullIntl($this, false); \Locale::setDefault($locale); @@ -233,41 +229,33 @@ class IntegerToLocalizedStringTransformerTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformDisallowsNaN() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new IntegerToLocalizedStringTransformer(); $transformer->reverseTransform('NaN'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformDisallowsNaN2() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new IntegerToLocalizedStringTransformer(); $transformer->reverseTransform('nan'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformDisallowsInfinity() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new IntegerToLocalizedStringTransformer(); $transformer->reverseTransform('∞'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformDisallowsNegativeInfinity() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new IntegerToLocalizedStringTransformer(); $transformer->reverseTransform('-∞'); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformerTest.php index 376c2ccaee..44f6ae02ae 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformerTest.php @@ -41,19 +41,15 @@ class IntlTimeZoneToStringTransformerTest extends TestCase $this->assertEquals([\IntlTimeZone::createTimeZone('Europe/Amsterdam')], $transformer->reverseTransform(['Europe/Amsterdam'])); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testInvalidTimezone() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); (new IntlTimeZoneToStringTransformer())->transform(1); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testUnknownTimezone() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); (new IntlTimeZoneToStringTransformer(true))->reverseTransform(['Foo/Bar']); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php index fd3f570d4c..c4e8c7a3d6 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php @@ -400,11 +400,9 @@ class NumberToLocalizedStringTransformerTest extends TestCase $this->assertEquals(1234.5, $transformer->reverseTransform('1234.5')); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDot() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); // Since we test against "de_DE", we need the full implementation IntlTestHelper::requireFullIntl($this, '4.8.1.1'); @@ -415,11 +413,9 @@ class NumberToLocalizedStringTransformerTest extends TestCase $transformer->reverseTransform('1.234.5'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDotWithNoGroupSep() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); // Since we test against "de_DE", we need the full implementation IntlTestHelper::requireFullIntl($this, '4.8.1.1'); @@ -459,11 +455,9 @@ class NumberToLocalizedStringTransformerTest extends TestCase $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5')); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsComma() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); IntlTestHelper::requireFullIntl($this, '4.8.1.1'); $transformer = new NumberToLocalizedStringTransformer(null, true); @@ -471,11 +465,9 @@ class NumberToLocalizedStringTransformerTest extends TestCase $transformer->reverseTransform('1,234,5'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsCommaWithNoGroupSep() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); IntlTestHelper::requireFullIntl($this, '4.8.1.1'); $transformer = new NumberToLocalizedStringTransformer(null, true); @@ -491,44 +483,37 @@ class NumberToLocalizedStringTransformerTest extends TestCase $this->assertEquals(1234.5, $transformer->reverseTransform('1234.5')); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testTransformExpectsNumeric() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new NumberToLocalizedStringTransformer(); $transformer->transform('foo'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformExpectsString() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform(1); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformExpectsValidNumber() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform('foo'); } /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException * @dataProvider nanRepresentationProvider - * * @see https://github.com/symfony/symfony/issues/3161 */ public function testReverseTransformDisallowsNaN($nan) { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform($nan); @@ -543,63 +528,51 @@ class NumberToLocalizedStringTransformerTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformDisallowsInfinity() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform('∞'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformDisallowsInfinity2() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform('∞,123'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformDisallowsNegativeInfinity() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform('-∞'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformDisallowsLeadingExtraCharacters() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform('foo123'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage The number contains unrecognized characters: "foo3" - */ public function testReverseTransformDisallowsCenteredExtraCharacters() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('The number contains unrecognized characters: "foo3"'); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform('12foo3'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage The number contains unrecognized characters: "foo8" - */ public function testReverseTransformDisallowsCenteredExtraCharactersMultibyte() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('The number contains unrecognized characters: "foo8"'); // Since we test against other locales, we need the full implementation IntlTestHelper::requireFullIntl($this, false); @@ -610,12 +583,10 @@ class NumberToLocalizedStringTransformerTest extends TestCase $transformer->reverseTransform("12\xc2\xa0345,67foo8"); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage The number contains unrecognized characters: "foo8" - */ public function testReverseTransformIgnoresTrailingSpacesInExceptionMessage() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('The number contains unrecognized characters: "foo8"'); // Since we test against other locales, we need the full implementation IntlTestHelper::requireFullIntl($this, false); @@ -626,23 +597,19 @@ class NumberToLocalizedStringTransformerTest extends TestCase $transformer->reverseTransform("12\xc2\xa0345,67foo8 \xc2\xa0\t"); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage The number contains unrecognized characters: "foo" - */ public function testReverseTransformDisallowsTrailingExtraCharacters() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('The number contains unrecognized characters: "foo"'); $transformer = new NumberToLocalizedStringTransformer(); $transformer->reverseTransform('123foo'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage The number contains unrecognized characters: "foo" - */ public function testReverseTransformDisallowsTrailingExtraCharactersMultibyte() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('The number contains unrecognized characters: "foo"'); // Since we test against other locales, we need the full implementation IntlTestHelper::requireFullIntl($this, false); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php index e2dfc481b3..06ef6cc736 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php @@ -145,11 +145,9 @@ class PercentToLocalizedStringTransformerTest extends TestCase $this->assertEquals(1234.5, $transformer->reverseTransform('1234.5')); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDot() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); // Since we test against "de_DE", we need the full implementation IntlTestHelper::requireFullIntl($this, '4.8.1.1'); @@ -160,11 +158,9 @@ class PercentToLocalizedStringTransformerTest extends TestCase $transformer->reverseTransform('1.234.5'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDotWithNoGroupSep() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); // Since we test against "de_DE", we need the full implementation IntlTestHelper::requireFullIntl($this, '4.8.1.1'); @@ -204,11 +200,9 @@ class PercentToLocalizedStringTransformerTest extends TestCase $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5')); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsComma() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); IntlTestHelper::requireFullIntl($this, '4.8.1.1'); $transformer = new PercentToLocalizedStringTransformer(1, 'integer'); @@ -216,11 +210,9 @@ class PercentToLocalizedStringTransformerTest extends TestCase $transformer->reverseTransform('1,234,5'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsCommaWithNoGroupSep() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); IntlTestHelper::requireFullIntl($this, '4.8.1.1'); $transformer = new PercentToLocalizedStringTransformer(1, 'integer'); @@ -246,34 +238,30 @@ class PercentToLocalizedStringTransformerTest extends TestCase $this->assertEquals(1234.5, $transformer->reverseTransform('1234.5')); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformDisallowsLeadingExtraCharacters() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new PercentToLocalizedStringTransformer(); $transformer->reverseTransform('foo123'); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage The number contains unrecognized characters: "foo3" - */ public function testReverseTransformDisallowsCenteredExtraCharacters() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('The number contains unrecognized characters: "foo3"'); $transformer = new PercentToLocalizedStringTransformer(); $transformer->reverseTransform('12foo3'); } /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage The number contains unrecognized characters: "foo8" * @requires extension mbstring */ public function testReverseTransformDisallowsCenteredExtraCharactersMultibyte() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('The number contains unrecognized characters: "foo8"'); // Since we test against other locales, we need the full implementation IntlTestHelper::requireFullIntl($this, false); @@ -284,24 +272,22 @@ class PercentToLocalizedStringTransformerTest extends TestCase $transformer->reverseTransform("12\xc2\xa0345,67foo8"); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage The number contains unrecognized characters: "foo" - */ public function testReverseTransformDisallowsTrailingExtraCharacters() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('The number contains unrecognized characters: "foo"'); $transformer = new PercentToLocalizedStringTransformer(); $transformer->reverseTransform('123foo'); } /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage The number contains unrecognized characters: "foo" * @requires extension mbstring */ public function testReverseTransformDisallowsTrailingExtraCharactersMultibyte() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('The number contains unrecognized characters: "foo"'); // Since we test against other locales, we need the full implementation IntlTestHelper::requireFullIntl($this, false); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/StringToFloatTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/StringToFloatTransformerTest.php index 2eae3121b6..d2c800be67 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/StringToFloatTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/StringToFloatTransformerTest.php @@ -49,20 +49,16 @@ class StringToFloatTransformerTest extends TestCase $this->assertSame($to, $transformer->transform($from)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testFailIfTransformingANonString(): void { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new StringToFloatTransformer(); $transformer->transform(1.0); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testFailIfTransformingANonNumericString(): void { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new StringToFloatTransformer(); $transformer->transform('foobar'); } @@ -93,11 +89,9 @@ class StringToFloatTransformerTest extends TestCase $this->assertSame($to, $transformer->reverseTransform($from)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testFailIfReverseTransformingANonNumeric(): void { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $transformer = new StringToFloatTransformer(); $transformer->reverseTransform('foobar'); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.php index 179ace5a6c..c02eb3573e 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.php @@ -108,11 +108,9 @@ class ValueToDuplicatesTransformerTest extends TestCase $this->assertSame('0', $this->transformer->reverseTransform($input)); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformPartiallyNull() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $input = [ 'a' => 'Foo', 'b' => 'Foo', @@ -122,11 +120,9 @@ class ValueToDuplicatesTransformerTest extends TestCase $this->transformer->reverseTransform($input); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformDifferences() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $input = [ 'a' => 'Foo', 'b' => 'Bar', @@ -136,11 +132,9 @@ class ValueToDuplicatesTransformerTest extends TestCase $this->transformer->reverseTransform($input); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - */ public function testReverseTransformRequiresArray() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); $this->transformer->reverseTransform('12345'); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php index daf5d60d37..67545d6f29 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php @@ -185,10 +185,10 @@ abstract class MergeCollectionListenerTest extends TestCase /** * @dataProvider getBooleanMatrix2 - * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException */ public function testRequireArrayOrTraversable($allowAdd, $allowDelete) { + $this->expectException('Symfony\Component\Form\Exception\UnexpectedTypeException'); $newData = 'no array or traversable'; $event = new FormEvent($this->form, $newData); $listener = new MergeCollectionListener($allowAdd, $allowDelete); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php index a1775efe9f..4c3ff17b4c 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php @@ -69,11 +69,9 @@ class ResizeFormListenerTest extends TestCase $this->assertTrue($this->form->has('2')); } - /** - * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException - */ public function testPreSetDataRequiresArrayOrTraversable() { + $this->expectException('Symfony\Component\Form\Exception\UnexpectedTypeException'); $data = 'no array or traversable'; $event = new FormEvent($this->form, $data); $listener = new ResizeFormListener('text', [], false, false); @@ -204,11 +202,9 @@ class ResizeFormListenerTest extends TestCase $this->assertEquals($data, $event->getData()); } - /** - * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException - */ public function testOnSubmitNormDataRequiresArrayOrTraversable() { + $this->expectException('Symfony\Component\Form\Exception\UnexpectedTypeException'); $data = 'no array or traversable'; $event = new FormEvent($this->form, $data); $listener = new ResizeFormListener('text', [], false, false); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/BirthdayTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/BirthdayTypeTest.php index ffadf8c844..01e08d09ff 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/BirthdayTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/BirthdayTypeTest.php @@ -11,18 +11,20 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; + /** * @author Stepan Anchugov */ class BirthdayTypeTest extends DateTypeTest { + use ForwardCompatTestTrait; + const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\BirthdayType'; - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testSetInvalidYearsOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'years' => 'bad value', ]); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/ButtonTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/ButtonTypeTest.php index 350602306f..98df91d7e8 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/ButtonTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/ButtonTypeTest.php @@ -11,11 +11,15 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; + /** * @author Bernhard Schussek */ class ButtonTypeTest extends BaseTypeTest { + use ForwardCompatTestTrait; + const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\ButtonType'; public function testCreateButtonInstances() @@ -24,14 +28,14 @@ class ButtonTypeTest extends BaseTypeTest } /** - * @expectedException \Symfony\Component\Form\Exception\BadMethodCallException - * @expectedExceptionMessage Buttons do not support empty data. * * @param string $emptyData * @param null $expectedData */ public function testSubmitNullUsesDefaultEmptyData($emptyData = 'empty', $expectedData = null) { + $this->expectException('Symfony\Component\Form\Exception\BadMethodCallException'); + $this->expectExceptionMessage('Buttons do not support empty data.'); parent::testSubmitNullUsesDefaultEmptyData($emptyData, $expectedData); } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/CheckboxTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/CheckboxTypeTest.php index d8f0cba025..265e5e2b09 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/CheckboxTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/CheckboxTypeTest.php @@ -194,11 +194,9 @@ class CheckboxTypeTest extends BaseTypeTest ]; } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testDontAllowNonArrayFalseValues() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->expectExceptionMessageRegExp('/"false_values" with value "invalid" is expected to be of type "array"/'); $this->factory->create(static::TESTED_TYPE, null, [ 'false_values' => 'invalid', diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.php index 33812c552c..af3ba6237b 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.php @@ -83,21 +83,17 @@ class ChoiceTypeTest extends BaseTypeTest $this->objectChoices = null; } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testChoicesOptionExpectsArrayOrTraversable() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'choices' => new \stdClass(), ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testChoiceLoaderOptionExpectsChoiceLoaderInterface() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'choice_loader' => new \stdClass(), ]); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/DateTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/DateTypeTest.php index a8513cceff..a2ab7ee9d8 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/DateTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/DateTypeTest.php @@ -38,21 +38,17 @@ class DateTypeTest extends BaseTypeTest \Locale::setDefault($this->defaultLocale); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testInvalidWidgetOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'widget' => 'fake_widget', ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testInvalidInputOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'input' => 'fake_input', ]); @@ -376,11 +372,10 @@ class DateTypeTest extends BaseTypeTest /** * This test is to check that the strings '0', '1', '2', '3' are not accepted * as valid IntlDateFormatter constants for FULL, LONG, MEDIUM or SHORT respectively. - * - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException */ public function testThrowExceptionIfFormatIsNoPattern() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'format' => '0', 'html5' => false, @@ -389,24 +384,20 @@ class DateTypeTest extends BaseTypeTest ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The "format" option should contain the letters "y", "M" and "d". Its current value is "yy". - */ public function testThrowExceptionIfFormatDoesNotContainYearMonthAndDay() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The "format" option should contain the letters "y", "M" and "d". Its current value is "yy".'); $this->factory->create(static::TESTED_TYPE, null, [ 'months' => [6, 7], 'format' => 'yy', ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The "format" option should contain the letters "y", "M" or "d". Its current value is "wrong". - */ public function testThrowExceptionIfFormatMissesYearMonthAndDayWithSingleTextWidget() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The "format" option should contain the letters "y", "M" or "d". Its current value is "wrong".'); $this->factory->create(static::TESTED_TYPE, null, [ 'widget' => 'single_text', 'format' => 'wrong', @@ -414,51 +405,41 @@ class DateTypeTest extends BaseTypeTest ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testThrowExceptionIfFormatIsNoConstant() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'format' => 105, ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testThrowExceptionIfFormatIsInvalid() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'format' => [], ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testThrowExceptionIfYearsIsInvalid() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'years' => 'bad value', ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testThrowExceptionIfMonthsIsInvalid() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'months' => 'bad value', ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testThrowExceptionIfDaysIsInvalid() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'days' => 'bad value', ]); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php index 2607f1d376..4dcb3c34a0 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Form\CallbackTransformer; use Symfony\Component\Form\DataMapperInterface; use Symfony\Component\Form\Exception\TransformationFailedException; @@ -59,6 +60,8 @@ class FormTest_AuthorWithoutRefSetter class FormTypeTest extends BaseTypeTest { + use ForwardCompatTestTrait; + const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\FormType'; public function testCreateFormInstances() @@ -168,11 +171,9 @@ class FormTypeTest extends BaseTypeTest ])); } - /** - * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException - */ public function testDataClassMustBeValidClassOrInterface() { + $this->expectException('Symfony\Component\Form\Exception\InvalidArgumentException'); $this->factory->createBuilder(static::TESTED_TYPE, null, [ 'data_class' => 'foobar', ]); @@ -337,11 +338,9 @@ class FormTypeTest extends BaseTypeTest $this->assertEquals('Bernhard', $author->firstName); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testAttributesException() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, ['attr' => '']); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/NumberTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/NumberTypeTest.php index 75e415fce2..08fd2d5406 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/NumberTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/NumberTypeTest.php @@ -80,24 +80,22 @@ class NumberTypeTest extends BaseTypeTest $this->assertSame('12345,68', $form->createView()->vars['value']); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage Expected a numeric string. - */ public function testStringInputWithFloatData(): void { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('Expected a numeric string.'); + $this->factory->create(static::TESTED_TYPE, 12345.6789, [ 'input' => 'string', 'scale' => 2, ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage Expected a numeric string. - */ public function testStringInputWithIntData(): void { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('Expected a numeric string.'); + $this->factory->create(static::TESTED_TYPE, 12345, [ 'input' => 'string', 'scale' => 2, @@ -182,11 +180,9 @@ class NumberTypeTest extends BaseTypeTest $this->assertSame('12345.55', $form->getViewData()); } - /** - * @expectedException \Symfony\Component\Form\Exception\LogicException - */ public function testGroupingNotAllowedWithHtml5Widget() { + $this->expectException('Symfony\Component\Form\Exception\LogicException'); $this->factory->create(static::TESTED_TYPE, null, [ 'grouping' => true, 'html5' => true, diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/RepeatedTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/RepeatedTypeTest.php index de99a9b9f1..3d49ae83f8 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/RepeatedTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/RepeatedTypeTest.php @@ -81,33 +81,27 @@ class RepeatedTypeTest extends BaseTypeTest $this->assertFalse($form['second']->isRequired()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testSetInvalidOptions() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'type' => TextTypeTest::TESTED_TYPE, 'options' => 'bad value', ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testSetInvalidFirstOptions() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'type' => TextTypeTest::TESTED_TYPE, 'first_options' => 'bad value', ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testSetInvalidSecondOptions() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'type' => TextTypeTest::TESTED_TYPE, 'second_options' => 'bad value', diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimeTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimeTypeTest.php index d5b4a11ced..b161ba99f7 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimeTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimeTypeTest.php @@ -11,11 +11,14 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\FormError; class TimeTypeTest extends BaseTypeTest { + use ForwardCompatTestTrait; + const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\TimeType'; public function testSubmitDateTime() @@ -425,12 +428,11 @@ class TimeTypeTest extends BaseTypeTest $this->assertSame(['hour' => '16', 'minute' => '9', 'second' => '10'], $form->getViewData()); } - /** - * @expectedException \Symfony\Component\Form\Exception\LogicException - * @expectedExceptionMessage Using different values for the "model_timezone" and "view_timezone" options without configuring a reference date is not supported. - */ public function testSetDataDifferentTimezonesWithoutReferenceDate() { + $this->expectException('Symfony\Component\Form\Exception\LogicException'); + $this->expectExceptionMessage('Using different values for the "model_timezone" and "view_timezone" options without configuring a reference date is not supported.'); + $form = $this->factory->create(static::TESTED_TYPE, null, [ 'model_timezone' => 'UTC', 'view_timezone' => 'Europe/Berlin', @@ -807,52 +809,42 @@ class TimeTypeTest extends BaseTypeTest $this->assertSame([$error], iterator_to_array($form->getErrors())); } - /** - * @expectedException \Symfony\Component\Form\Exception\InvalidConfigurationException - */ public function testInitializeWithSecondsAndWithoutMinutes() { + $this->expectException('Symfony\Component\Form\Exception\InvalidConfigurationException'); $this->factory->create(static::TESTED_TYPE, null, [ 'with_minutes' => false, 'with_seconds' => true, ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testThrowExceptionIfHoursIsInvalid() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'hours' => 'bad value', ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testThrowExceptionIfMinutesIsInvalid() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'minutes' => 'bad value', ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testThrowExceptionIfSecondsIsInvalid() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'seconds' => 'bad value', ]); } - /** - * @expectedException \Symfony\Component\Form\Exception\InvalidConfigurationException - */ public function testReferenceDateTimezoneMustMatchModelTimezone() { + $this->expectException('Symfony\Component\Form\Exception\InvalidConfigurationException'); $this->factory->create(static::TESTED_TYPE, null, [ 'model_timezone' => 'UTC', 'view_timezone' => 'Europe/Berlin', diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimezoneTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimezoneTypeTest.php index d514dc85a8..32582f99be 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimezoneTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/TimezoneTypeTest.php @@ -167,12 +167,10 @@ class TimezoneTypeTest extends BaseTypeTest $this->assertContains(new ChoiceView('Etc/UTC', 'Etc/UTC', 'за всесвітнім координованим часом'), $choices, '', false, false); } - /** - * @expectedException \Symfony\Component\Form\Exception\LogicException - * @expectedExceptionMessage The "choice_translation_locale" option can only be used if the "intl" option is set to true. - */ public function testChoiceTranslationLocaleOptionWithoutIntl() { + $this->expectException('Symfony\Component\Form\Exception\LogicException'); + $this->expectExceptionMessage('The "choice_translation_locale" option can only be used if the "intl" option is set to true.'); $this->factory->create(static::TESTED_TYPE, null, [ 'choice_translation_locale' => 'uk', ]); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/UrlTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/UrlTypeTest.php index a5608557dd..4ea231dc3a 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/UrlTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/UrlTypeTest.php @@ -11,8 +11,12 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; + class UrlTypeTest extends TextTypeTest { + use ForwardCompatTestTrait; + const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\UrlType'; public function testSubmitAddsDefaultProtocolIfNoneIsIncluded() @@ -73,11 +77,9 @@ class UrlTypeTest extends TextTypeTest $this->assertSame('www.domain.com', $form->getViewData()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testThrowExceptionIfDefaultProtocolIsInvalid() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->factory->create(static::TESTED_TYPE, null, [ 'default_protocol' => [], ]); diff --git a/src/Symfony/Component/Form/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php b/src/Symfony/Component/Form/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php index 62a1ec286d..992d2f692f 100644 --- a/src/Symfony/Component/Form/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Extension\DependencyInjection\DependencyInjectionExtension; @@ -20,6 +21,8 @@ use Symfony\Component\Form\FormTypeGuesserInterface; class DependencyInjectionExtensionTest extends TestCase { + use ForwardCompatTestTrait; + public function testGetTypeExtensions() { $typeExtension1 = new TestTypeExtension(); @@ -41,11 +44,9 @@ class DependencyInjectionExtensionTest extends TestCase $this->assertSame([$typeExtension3, $typeExtension4], $extension->getTypeExtensions('other')); } - /** - * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException - */ public function testThrowExceptionForInvalidExtendedType() { + $this->expectException('Symfony\Component\Form\Exception\InvalidArgumentException'); $extensions = [ 'unmatched' => new \ArrayIterator([new TestTypeExtension()]), ]; diff --git a/src/Symfony/Component/Form/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.php b/src/Symfony/Component/Form/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.php index dc082505a1..2de65c7c18 100644 --- a/src/Symfony/Component/Form/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Tests\Extension\HttpFoundation; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler; use Symfony\Component\Form\Tests\AbstractRequestHandlerTest; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -21,19 +22,17 @@ use Symfony\Component\HttpFoundation\Request; */ class HttpFoundationRequestHandlerTest extends AbstractRequestHandlerTest { - /** - * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException - */ + use ForwardCompatTestTrait; + public function testRequestShouldNotBeNull() { + $this->expectException('Symfony\Component\Form\Exception\UnexpectedTypeException'); $this->requestHandler->handleRequest($this->createForm('name', 'GET')); } - /** - * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException - */ public function testRequestShouldBeInstanceOfRequest() { + $this->expectException('Symfony\Component\Form\Exception\UnexpectedTypeException'); $this->requestHandler->handleRequest($this->createForm('name', 'GET'), new \stdClass()); } diff --git a/src/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationPathTest.php b/src/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationPathTest.php index 7a6602d27e..889cc6bd8e 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationPathTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationPathTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\ViolationMapper; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationPath; /** @@ -19,6 +20,8 @@ use Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationPath; */ class ViolationPathTest extends TestCase { + use ForwardCompatTestTrait; + public function providePaths() { return [ @@ -140,21 +143,17 @@ class ViolationPathTest extends TestCase $this->assertEquals('street', $path->getElement(1)); } - /** - * @expectedException \OutOfBoundsException - */ public function testGetElementDoesNotAcceptInvalidIndices() { + $this->expectException('OutOfBoundsException'); $path = new ViolationPath('children[address].data[street].name'); $path->getElement(3); } - /** - * @expectedException \OutOfBoundsException - */ public function testGetElementDoesNotAcceptNegativeIndices() { + $this->expectException('OutOfBoundsException'); $path = new ViolationPath('children[address].data[street].name'); $path->getElement(-1); @@ -168,21 +167,17 @@ class ViolationPathTest extends TestCase $this->assertTrue($path->isProperty(2)); } - /** - * @expectedException \OutOfBoundsException - */ public function testIsPropertyDoesNotAcceptInvalidIndices() { + $this->expectException('OutOfBoundsException'); $path = new ViolationPath('children[address].data[street].name'); $path->isProperty(3); } - /** - * @expectedException \OutOfBoundsException - */ public function testIsPropertyDoesNotAcceptNegativeIndices() { + $this->expectException('OutOfBoundsException'); $path = new ViolationPath('children[address].data[street].name'); $path->isProperty(-1); @@ -196,21 +191,17 @@ class ViolationPathTest extends TestCase $this->assertFalse($path->isIndex(2)); } - /** - * @expectedException \OutOfBoundsException - */ public function testIsIndexDoesNotAcceptInvalidIndices() { + $this->expectException('OutOfBoundsException'); $path = new ViolationPath('children[address].data[street].name'); $path->isIndex(3); } - /** - * @expectedException \OutOfBoundsException - */ public function testIsIndexDoesNotAcceptNegativeIndices() { + $this->expectException('OutOfBoundsException'); $path = new ViolationPath('children[address].data[street].name'); $path->isIndex(-1); @@ -225,21 +216,17 @@ class ViolationPathTest extends TestCase $this->assertFalse($path->mapsForm(2)); } - /** - * @expectedException \OutOfBoundsException - */ public function testMapsFormDoesNotAcceptInvalidIndices() { + $this->expectException('OutOfBoundsException'); $path = new ViolationPath('children[address].data[street].name'); $path->mapsForm(3); } - /** - * @expectedException \OutOfBoundsException - */ public function testMapsFormDoesNotAcceptNegativeIndices() { + $this->expectException('OutOfBoundsException'); $path = new ViolationPath('children[address].data[street].name'); $path->mapsForm(-1); diff --git a/src/Symfony/Component/Form/Tests/FormFactoryTest.php b/src/Symfony/Component/Form/Tests/FormFactoryTest.php index 965485cf2c..9250ee4cf2 100644 --- a/src/Symfony/Component/Form/Tests/FormFactoryTest.php +++ b/src/Symfony/Component/Form/Tests/FormFactoryTest.php @@ -149,21 +149,17 @@ class FormFactoryTest extends TestCase $this->assertSame($this->builder, $this->factory->createNamedBuilder('name', 'type', 'DATA', $options)); } - /** - * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException - * @expectedExceptionMessage Expected argument of type "string", "stdClass" given - */ public function testCreateNamedBuilderThrowsUnderstandableException() { + $this->expectException('Symfony\Component\Form\Exception\UnexpectedTypeException'); + $this->expectExceptionMessage('Expected argument of type "string", "stdClass" given'); $this->factory->createNamedBuilder('name', new \stdClass()); } - /** - * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException - * @expectedExceptionMessage Expected argument of type "string", "stdClass" given - */ public function testCreateThrowsUnderstandableException() { + $this->expectException('Symfony\Component\Form\Exception\UnexpectedTypeException'); + $this->expectExceptionMessage('Expected argument of type "string", "stdClass" given'); $this->factory->create(new \stdClass()); } diff --git a/src/Symfony/Component/Form/Tests/FormRegistryTest.php b/src/Symfony/Component/Form/Tests/FormRegistryTest.php index 8d72db3391..21096b746d 100644 --- a/src/Symfony/Component/Form/Tests/FormRegistryTest.php +++ b/src/Symfony/Component/Form/Tests/FormRegistryTest.php @@ -105,19 +105,15 @@ class FormRegistryTest extends TestCase $this->assertSame($resolvedType, $this->registry->getType('Symfony\Component\Form\Tests\Fixtures\FooType')); } - /** - * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException - */ public function testFailIfUnregisteredTypeNoClass() { + $this->expectException('Symfony\Component\Form\Exception\InvalidArgumentException'); $this->registry->getType('Symfony\Blubb'); } - /** - * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException - */ public function testFailIfUnregisteredTypeNoFormType() { + $this->expectException('Symfony\Component\Form\Exception\InvalidArgumentException'); $this->registry->getType('stdClass'); } @@ -163,12 +159,10 @@ class FormRegistryTest extends TestCase $this->assertSame($resolvedType, $this->registry->getType(\get_class($type))); } - /** - * @expectedException \Symfony\Component\Form\Exception\LogicException - * @expectedExceptionMessage Circular reference detected for form type "Symfony\Component\Form\Tests\Fixtures\FormWithSameParentType" (Symfony\Component\Form\Tests\Fixtures\FormWithSameParentType > Symfony\Component\Form\Tests\Fixtures\FormWithSameParentType). - */ public function testFormCannotHaveItselfAsAParent() { + $this->expectException('Symfony\Component\Form\Exception\LogicException'); + $this->expectExceptionMessage('Circular reference detected for form type "Symfony\Component\Form\Tests\Fixtures\FormWithSameParentType" (Symfony\Component\Form\Tests\Fixtures\FormWithSameParentType > Symfony\Component\Form\Tests\Fixtures\FormWithSameParentType).'); $type = new FormWithSameParentType(); $this->extension2->addType($type); @@ -176,12 +170,10 @@ class FormRegistryTest extends TestCase $this->registry->getType(FormWithSameParentType::class); } - /** - * @expectedException \Symfony\Component\Form\Exception\LogicException - * @expectedExceptionMessage Circular reference detected for form type "Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeFoo" (Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeFoo > Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeBar > Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeBaz > Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeFoo). - */ public function testRecursiveFormDependencies() { + $this->expectException('Symfony\Component\Form\Exception\LogicException'); + $this->expectExceptionMessage('Circular reference detected for form type "Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeFoo" (Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeFoo > Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeBar > Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeBaz > Symfony\Component\Form\Tests\Fixtures\RecursiveFormTypeFoo).'); $foo = new RecursiveFormTypeFoo(); $bar = new RecursiveFormTypeBar(); $baz = new RecursiveFormTypeBaz(); @@ -193,11 +185,9 @@ class FormRegistryTest extends TestCase $this->registry->getType(RecursiveFormTypeFoo::class); } - /** - * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException - */ public function testGetTypeThrowsExceptionIfTypeNotFound() { + $this->expectException('Symfony\Component\Form\Exception\InvalidArgumentException'); $this->registry->getType('bar'); } diff --git a/src/Symfony/Component/Form/Tests/FormRendererTest.php b/src/Symfony/Component/Form/Tests/FormRendererTest.php index 43d0bec67a..8c85fd84ff 100644 --- a/src/Symfony/Component/Form/Tests/FormRendererTest.php +++ b/src/Symfony/Component/Form/Tests/FormRendererTest.php @@ -29,12 +29,11 @@ class FormRendererTest extends TestCase $this->assertEquals('Is active', $renderer->humanize('isActive')); } - /** - * @expectedException \Symfony\Component\Form\Exception\BadMethodCallException - * @expectedExceptionMessage Field "foo" has already been rendered, save the result of previous render call to a variable and output that instead. - */ public function testRenderARenderedField() { + $this->expectException('Symfony\Component\Form\Exception\BadMethodCallException'); + $this->expectExceptionMessage('Field "foo" has already been rendered, save the result of previous render call to a variable and output that instead.'); + $formView = new FormView(); $formView->vars['name'] = 'foo'; $formView->setRendered(); diff --git a/src/Symfony/Component/Form/Tests/Guess/GuessTest.php b/src/Symfony/Component/Form/Tests/Guess/GuessTest.php index eea423bb9d..304eba3fa6 100644 --- a/src/Symfony/Component/Form/Tests/Guess/GuessTest.php +++ b/src/Symfony/Component/Form/Tests/Guess/GuessTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Guess; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Form\Guess\Guess; class TestGuess extends Guess @@ -20,6 +21,8 @@ class TestGuess extends Guess class GuessTest extends TestCase { + use ForwardCompatTestTrait; + public function testGetBestGuessReturnsGuessWithHighestConfidence() { $guess1 = new TestGuess(Guess::MEDIUM_CONFIDENCE); @@ -29,11 +32,9 @@ class GuessTest extends TestCase $this->assertSame($guess3, Guess::getBestGuess([$guess1, $guess2, $guess3])); } - /** - * @expectedException \InvalidArgumentException - */ public function testGuessExpectsValidConfidence() { + $this->expectException('\InvalidArgumentException'); new TestGuess(5); } } diff --git a/src/Symfony/Component/Form/Tests/NativeRequestHandlerTest.php b/src/Symfony/Component/Form/Tests/NativeRequestHandlerTest.php index ab66904617..12230a803d 100644 --- a/src/Symfony/Component/Form/Tests/NativeRequestHandlerTest.php +++ b/src/Symfony/Component/Form/Tests/NativeRequestHandlerTest.php @@ -51,11 +51,9 @@ class NativeRequestHandlerTest extends AbstractRequestHandlerTest $_SERVER = self::$serverBackup; } - /** - * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException - */ public function testRequestShouldBeNull() { + $this->expectException('Symfony\Component\Form\Exception\UnexpectedTypeException'); $this->requestHandler->handleRequest($this->createForm('name', 'GET'), 'request'); } diff --git a/src/Symfony/Component/Form/Tests/ResolvedFormTypeTest.php b/src/Symfony/Component/Form/Tests/ResolvedFormTypeTest.php index ba55993cd6..e3dc671bfb 100644 --- a/src/Symfony/Component/Form/Tests/ResolvedFormTypeTest.php +++ b/src/Symfony/Component/Form/Tests/ResolvedFormTypeTest.php @@ -182,12 +182,10 @@ class ResolvedFormTypeTest extends TestCase $this->assertSame('\stdClass', $builder->getDataClass()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\MissingOptionsException - * @expectedExceptionMessage An error has occurred resolving the options of the form "stdClass": The required option "foo" is missing. - */ public function testFailsCreateBuilderOnInvalidFormOptionsResolution() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\MissingOptionsException'); + $this->expectExceptionMessage('An error has occurred resolving the options of the form "stdClass": The required option "foo" is missing.'); $optionsResolver = (new OptionsResolver()) ->setRequired('foo') ; diff --git a/src/Symfony/Component/Form/Tests/SimpleFormTest.php b/src/Symfony/Component/Form/Tests/SimpleFormTest.php index 284738313b..a814b34532 100644 --- a/src/Symfony/Component/Form/Tests/SimpleFormTest.php +++ b/src/Symfony/Component/Form/Tests/SimpleFormTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Tests; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Form; @@ -54,6 +55,8 @@ class SimpleFormTest_Traversable implements \IteratorAggregate class SimpleFormTest extends AbstractFormTest { + use ForwardCompatTestTrait; + /** * @dataProvider provideFormNames */ @@ -94,12 +97,10 @@ class SimpleFormTest extends AbstractFormTest $this->assertSame('bar', $form->getViewData()); } - /** - * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException - * @expectedExceptionMessage Unable to transform data for property path "name": No mapping for value "arg" - */ public function testDataTransformationFailure() { + $this->expectException('Symfony\Component\Form\Exception\TransformationFailedException'); + $this->expectExceptionMessage('Unable to transform data for property path "name": No mapping for value "arg"'); $model = new FixedDataTransformer([ 'default' => 'foo', ]); @@ -160,11 +161,9 @@ class SimpleFormTest extends AbstractFormTest $this->assertNull($form->getData()); } - /** - * @expectedException \Symfony\Component\Form\Exception\AlreadySubmittedException - */ public function testSubmitThrowsExceptionIfAlreadySubmitted() { + $this->expectException('Symfony\Component\Form\Exception\AlreadySubmittedException'); $this->form->submit([]); $this->form->submit([]); } @@ -354,11 +353,9 @@ class SimpleFormTest extends AbstractFormTest $this->assertCount(0, $this->form->getErrors()); } - /** - * @expectedException \Symfony\Component\Form\Exception\AlreadySubmittedException - */ public function testSetParentThrowsExceptionIfAlreadySubmitted() { + $this->expectException('Symfony\Component\Form\Exception\AlreadySubmittedException'); $this->form->submit([]); $this->form->setParent($this->getBuilder('parent')->getForm()); } @@ -376,11 +373,9 @@ class SimpleFormTest extends AbstractFormTest $this->assertFalse($this->form->isSubmitted()); } - /** - * @expectedException \Symfony\Component\Form\Exception\AlreadySubmittedException - */ public function testSetDataThrowsExceptionIfAlreadySubmitted() { + $this->expectException('Symfony\Component\Form\Exception\AlreadySubmittedException'); $this->form->submit([]); $this->form->setData(null); } @@ -779,12 +774,10 @@ class SimpleFormTest extends AbstractFormTest $this->assertNull($form->getParent()); } - /** - * @expectedException \Symfony\Component\Form\Exception\LogicException - * @expectedExceptionMessage A form with an empty name cannot have a parent form. - */ public function testFormCannotHaveEmptyNameNotInRootLevel() { + $this->expectException('Symfony\Component\Form\Exception\LogicException'); + $this->expectExceptionMessage('A form with an empty name cannot have a parent form.'); $this->getBuilder() ->setCompound(true) ->setDataMapper($this->getDataMapper()) @@ -891,11 +884,9 @@ class SimpleFormTest extends AbstractFormTest $this->assertSame($arrayAccess, $form->getViewData()); } - /** - * @expectedException \Symfony\Component\Form\Exception\LogicException - */ public function testViewDataMustBeObjectIfDataClassIsSet() { + $this->expectException('Symfony\Component\Form\Exception\LogicException'); $config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher); $config->addViewTransformer(new FixedDataTransformer([ '' => '', @@ -906,12 +897,10 @@ class SimpleFormTest extends AbstractFormTest $form->setData('foo'); } - /** - * @expectedException \Symfony\Component\Form\Exception\RuntimeException - * @expectedExceptionMessage A cycle was detected. Listeners to the PRE_SET_DATA event must not call setData(). You should call setData() on the FormEvent object instead. - */ public function testSetDataCannotInvokeItself() { + $this->expectException('Symfony\Component\Form\Exception\RuntimeException'); + $this->expectExceptionMessage('A cycle was detected. Listeners to the PRE_SET_DATA event must not call setData(). You should call setData() on the FormEvent object instead.'); // Cycle detection to prevent endless loops $config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher); $config->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { @@ -980,11 +969,9 @@ class SimpleFormTest extends AbstractFormTest $this->assertSame('view[foo]', $parent->get('child')->getViewData()); } - /** - * @expectedException \Symfony\Component\Form\Exception\RuntimeException - */ public function testInheritDataDisallowsSetData() { + $this->expectException('Symfony\Component\Form\Exception\RuntimeException'); $form = $this->getBuilder() ->setInheritData(true) ->getForm(); @@ -992,11 +979,9 @@ class SimpleFormTest extends AbstractFormTest $form->setData('foo'); } - /** - * @expectedException \Symfony\Component\Form\Exception\RuntimeException - */ public function testGetDataRequiresParentToBeSetIfInheritData() { + $this->expectException('Symfony\Component\Form\Exception\RuntimeException'); $form = $this->getBuilder() ->setInheritData(true) ->getForm(); @@ -1004,11 +989,9 @@ class SimpleFormTest extends AbstractFormTest $form->getData(); } - /** - * @expectedException \Symfony\Component\Form\Exception\RuntimeException - */ public function testGetNormDataRequiresParentToBeSetIfInheritData() { + $this->expectException('Symfony\Component\Form\Exception\RuntimeException'); $form = $this->getBuilder() ->setInheritData(true) ->getForm(); @@ -1016,11 +999,9 @@ class SimpleFormTest extends AbstractFormTest $form->getNormData(); } - /** - * @expectedException \Symfony\Component\Form\Exception\RuntimeException - */ public function testGetViewDataRequiresParentToBeSetIfInheritData() { + $this->expectException('Symfony\Component\Form\Exception\RuntimeException'); $form = $this->getBuilder() ->setInheritData(true) ->getForm(); @@ -1068,11 +1049,9 @@ class SimpleFormTest extends AbstractFormTest $form->initialize(); } - /** - * @expectedException \Symfony\Component\Form\Exception\RuntimeException - */ public function testInitializeFailsIfParent() { + $this->expectException('Symfony\Component\Form\Exception\RuntimeException'); $parent = $this->getBuilder()->setRequired(false)->getForm(); $child = $this->getBuilder()->setRequired(true)->getForm(); @@ -1081,12 +1060,10 @@ class SimpleFormTest extends AbstractFormTest $child->initialize(); } - /** - * @expectedException \Symfony\Component\Form\Exception\RuntimeException - * @expectedExceptionMessage A cycle was detected. Listeners to the PRE_SET_DATA event must not call getData() if the form data has not already been set. You should call getData() on the FormEvent object instead. - */ public function testCannotCallGetDataInPreSetDataListenerIfDataHasNotAlreadyBeenSet() { + $this->expectException('Symfony\Component\Form\Exception\RuntimeException'); + $this->expectExceptionMessage('A cycle was detected. Listeners to the PRE_SET_DATA event must not call getData() if the form data has not already been set. You should call getData() on the FormEvent object instead.'); $config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher); $config->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { $event->getForm()->getData(); @@ -1096,12 +1073,10 @@ class SimpleFormTest extends AbstractFormTest $form->setData('foo'); } - /** - * @expectedException \Symfony\Component\Form\Exception\RuntimeException - * @expectedExceptionMessage A cycle was detected. Listeners to the PRE_SET_DATA event must not call getNormData() if the form data has not already been set. - */ public function testCannotCallGetNormDataInPreSetDataListener() { + $this->expectException('Symfony\Component\Form\Exception\RuntimeException'); + $this->expectExceptionMessage('A cycle was detected. Listeners to the PRE_SET_DATA event must not call getNormData() if the form data has not already been set.'); $config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher); $config->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { $event->getForm()->getNormData(); @@ -1111,12 +1086,10 @@ class SimpleFormTest extends AbstractFormTest $form->setData('foo'); } - /** - * @expectedException \Symfony\Component\Form\Exception\RuntimeException - * @expectedExceptionMessage A cycle was detected. Listeners to the PRE_SET_DATA event must not call getViewData() if the form data has not already been set. - */ public function testCannotCallGetViewDataInPreSetDataListener() { + $this->expectException('Symfony\Component\Form\Exception\RuntimeException'); + $this->expectExceptionMessage('A cycle was detected. Listeners to the PRE_SET_DATA event must not call getViewData() if the form data has not already been set.'); $config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher); $config->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { $event->getForm()->getViewData(); diff --git a/src/Symfony/Component/Form/Tests/Util/OrderedHashMapTest.php b/src/Symfony/Component/Form/Tests/Util/OrderedHashMapTest.php index 01e76d87eb..649cb05ada 100644 --- a/src/Symfony/Component/Form/Tests/Util/OrderedHashMapTest.php +++ b/src/Symfony/Component/Form/Tests/Util/OrderedHashMapTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Util; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Form\Util\OrderedHashMap; /** @@ -19,6 +20,8 @@ use Symfony\Component\Form\Util\OrderedHashMap; */ class OrderedHashMapTest extends TestCase { + use ForwardCompatTestTrait; + public function testGet() { $map = new OrderedHashMap(); @@ -27,11 +30,9 @@ class OrderedHashMapTest extends TestCase $this->assertSame(1, $map['first']); } - /** - * @expectedException \OutOfBoundsException - */ public function testGetNonExistingFails() { + $this->expectException('OutOfBoundsException'); $map = new OrderedHashMap(); $map['first']; diff --git a/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php b/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php index f39771a46e..7971b79143 100644 --- a/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php +++ b/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php @@ -176,39 +176,31 @@ class HttpClientTraitTest extends TestCase $this->assertSame(['Authorization: Bearer foobar'], $options['normalized_headers']['authorization']); } - /** - * @expectedException \Symfony\Component\HttpClient\Exception\InvalidArgumentException - * @expectedExceptionMessage Option "auth_bearer" must be a string containing only characters from the base 64 alphabet, object given. - */ public function testInvalidAuthBearerOption() { + $this->expectException('Symfony\Component\HttpClient\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Option "auth_bearer" must be a string containing only characters from the base 64 alphabet, object given.'); self::prepareRequest('POST', 'http://example.com', ['auth_bearer' => new \stdClass()], HttpClientInterface::OPTIONS_DEFAULTS); } - /** - * @expectedException \Symfony\Component\HttpClient\Exception\InvalidArgumentException - * @expectedExceptionMessage Option "auth_bearer" must be a string containing only characters from the base 64 alphabet, invalid string given. - */ public function testInvalidAuthBearerValue() { + $this->expectException('Symfony\Component\HttpClient\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Option "auth_bearer" must be a string containing only characters from the base 64 alphabet, invalid string given.'); self::prepareRequest('POST', 'http://example.com', ['auth_bearer' => "a\nb"], HttpClientInterface::OPTIONS_DEFAULTS); } - /** - * @expectedException \Symfony\Component\HttpClient\Exception\InvalidArgumentException - * @expectedExceptionMessage Define either the "auth_basic" or the "auth_bearer" option, setting both is not supported. - */ public function testSetAuthBasicAndBearerOptions() { + $this->expectException('Symfony\Component\HttpClient\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Define either the "auth_basic" or the "auth_bearer" option, setting both is not supported.'); self::prepareRequest('POST', 'http://example.com', ['auth_bearer' => 'foo', 'auth_basic' => 'foo:bar'], HttpClientInterface::OPTIONS_DEFAULTS); } - /** - * @expectedException \Symfony\Component\HttpClient\Exception\InvalidArgumentException - * @expectedExceptionMessage Define either the "json" or the "body" option, setting both is not supported - */ public function testSetJSONAndBodyOptions() { + $this->expectException('Symfony\Component\HttpClient\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Define either the "json" or the "body" option, setting both is not supported'); self::prepareRequest('POST', 'http://example.com', ['json' => ['foo' => 'bar'], 'body' => ''], HttpClientInterface::OPTIONS_DEFAULTS); } @@ -247,21 +239,17 @@ class HttpClientTraitTest extends TestCase self::assertSame($expected, $this->normalizePeerFingerprint($fingerprint)); } - /** - * @expectedException \Symfony\Component\HttpClient\Exception\InvalidArgumentException - * @expectedExceptionMessage Cannot auto-detect fingerprint algorithm for "foo". - */ public function testNormalizePeerFingerprintException() { + $this->expectException('Symfony\Component\HttpClient\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Cannot auto-detect fingerprint algorithm for "foo".'); $this->normalizePeerFingerprint('foo'); } - /** - * @expectedException \Symfony\Component\HttpClient\Exception\InvalidArgumentException - * @expectedExceptionMessage Option "peer_fingerprint" must be string or array, object given. - */ public function testNormalizePeerFingerprintTypeException() { + $this->expectException('Symfony\Component\HttpClient\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Option "peer_fingerprint" must be string or array, object given.'); $fingerprint = new \stdClass(); $this->normalizePeerFingerprint($fingerprint); diff --git a/src/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.php b/src/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.php index e0df45c539..06b0668f7c 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.php @@ -49,11 +49,9 @@ class BinaryFileResponseTest extends ResponseTestCase $this->assertSame('fööö.html', $response->getFile()->getFilename()); } - /** - * @expectedException \LogicException - */ public function testSetContent() { + $this->expectException('LogicException'); $response = new BinaryFileResponse(__FILE__); $response->setContent('foo'); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/CookieTest.php b/src/Symfony/Component/HttpFoundation/Tests/CookieTest.php index 4aa32eea45..022fdab3f8 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/CookieTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/CookieTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Cookie; /** @@ -24,6 +25,8 @@ use Symfony\Component\HttpFoundation\Cookie; */ class CookieTest extends TestCase { + use ForwardCompatTestTrait; + public function invalidNames() { return [ @@ -41,18 +44,16 @@ class CookieTest extends TestCase /** * @dataProvider invalidNames - * @expectedException \InvalidArgumentException */ public function testInstantiationThrowsExceptionIfCookieNameContainsInvalidCharacters($name) { + $this->expectException('InvalidArgumentException'); Cookie::create($name); } - /** - * @expectedException \InvalidArgumentException - */ public function testInvalidExpiration() { + $this->expectException('InvalidArgumentException'); Cookie::create('MyCookie', 'foo', 'bar'); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/ExpressionRequestMatcherTest.php b/src/Symfony/Component/HttpFoundation/Tests/ExpressionRequestMatcherTest.php index 2afdade67d..e750f39e68 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/ExpressionRequestMatcherTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/ExpressionRequestMatcherTest.php @@ -12,17 +12,18 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Symfony\Component\HttpFoundation\ExpressionRequestMatcher; use Symfony\Component\HttpFoundation\Request; class ExpressionRequestMatcherTest extends TestCase { - /** - * @expectedException \LogicException - */ + use ForwardCompatTestTrait; + public function testWhenNoExpressionIsSet() { + $this->expectException('LogicException'); $expressionRequestMatcher = new ExpressionRequestMatcher(); $expressionRequestMatcher->matches(new Request()); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.php b/src/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.php index ca7259aed8..3695fcdf5e 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.php @@ -145,11 +145,9 @@ class UploadedFileTest extends TestCase $this->assertEquals('gif', $file->getClientOriginalExtension()); } - /** - * @expectedException \Symfony\Component\HttpFoundation\File\Exception\FileException - */ public function testMoveLocalFileIsNotAllowed() { + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileException'); $file = new UploadedFile( __DIR__.'/Fixtures/test.gif', 'original.gif', diff --git a/src/Symfony/Component/HttpFoundation/Tests/FileBagTest.php b/src/Symfony/Component/HttpFoundation/Tests/FileBagTest.php index 6f2a33d3cc..e830ba47d2 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/FileBagTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/FileBagTest.php @@ -26,11 +26,9 @@ class FileBagTest extends TestCase { use ForwardCompatTestTrait; - /** - * @expectedException \InvalidArgumentException - */ public function testFileMustBeAnArrayOrUploadedFile() { + $this->expectException('InvalidArgumentException'); new FileBag(['file' => 'foo']); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/HeaderBagTest.php b/src/Symfony/Component/HttpFoundation/Tests/HeaderBagTest.php index 6c4915f2e4..3eff568409 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/HeaderBagTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/HeaderBagTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\HeaderBag; class HeaderBagTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $bag = new HeaderBag(['foo' => 'bar']); @@ -48,11 +51,9 @@ class HeaderBagTest extends TestCase $this->assertInstanceOf('DateTime', $headerDate); } - /** - * @expectedException \RuntimeException - */ public function testGetDateException() { + $this->expectException('RuntimeException'); $bag = new HeaderBag(['foo' => 'Tue']); $headerDate = $bag->getDate('foo'); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/HeaderUtilsTest.php b/src/Symfony/Component/HttpFoundation/Tests/HeaderUtilsTest.php index 2f82dc4e67..d2b19ca84d 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/HeaderUtilsTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/HeaderUtilsTest.php @@ -83,11 +83,9 @@ class HeaderUtilsTest extends TestCase $this->assertEquals('foo \\ bar', HeaderUtils::unquote('"foo \\\\ bar"')); } - /** - * @expectedException \InvalidArgumentException - */ public function testMakeDispositionInvalidDisposition() { + $this->expectException('InvalidArgumentException'); HeaderUtils::makeDisposition('invalid', 'foo.html'); } @@ -113,10 +111,10 @@ class HeaderUtilsTest extends TestCase /** * @dataProvider provideMakeDispositionFail - * @expectedException \InvalidArgumentException */ public function testMakeDispositionFail($disposition, $filename) { + $this->expectException('InvalidArgumentException'); HeaderUtils::makeDisposition($disposition, $filename); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/IpUtilsTest.php b/src/Symfony/Component/HttpFoundation/Tests/IpUtilsTest.php index c7f76b5de2..338da1d25c 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/IpUtilsTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/IpUtilsTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\IpUtils; class IpUtilsTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getIpv4Data */ @@ -73,11 +76,11 @@ class IpUtilsTest extends TestCase } /** - * @expectedException \RuntimeException * @requires extension sockets */ public function testAnIpv6WithOptionDisabledIpv6() { + $this->expectException('RuntimeException'); if (\defined('AF_INET6')) { $this->markTestSkipped('Only works when PHP is compiled with the option "disable-ipv6".'); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/JsonResponseTest.php b/src/Symfony/Component/HttpFoundation/Tests/JsonResponseTest.php index b7482d0339..893e4cb896 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/JsonResponseTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/JsonResponseTest.php @@ -210,29 +210,23 @@ class JsonResponseTest extends TestCase $this->assertSame('{"foo":"bar"}', $response->getContent()); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetCallbackInvalidIdentifier() { + $this->expectException('InvalidArgumentException'); $response = new JsonResponse('foo'); $response->setCallback('+invalid'); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetContent() { + $this->expectException('InvalidArgumentException'); JsonResponse::create("\xB1\x31"); } - /** - * @expectedException \Exception - * @expectedExceptionMessage This error is expected - */ public function testSetContentJsonSerializeError() { + $this->expectException('Exception'); + $this->expectExceptionMessage('This error is expected'); if (!interface_exists('JsonSerializable', false)) { $this->markTestSkipped('JsonSerializable is required.'); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/RedirectResponseTest.php b/src/Symfony/Component/HttpFoundation/Tests/RedirectResponseTest.php index 24d703d52b..e67fbe7273 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/RedirectResponseTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/RedirectResponseTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\RedirectResponse; class RedirectResponseTest extends TestCase { + use ForwardCompatTestTrait; + public function testGenerateMetaRedirect() { $response = new RedirectResponse('foo.bar'); @@ -26,20 +29,16 @@ class RedirectResponseTest extends TestCase )); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Cannot redirect to an empty URL. - */ public function testRedirectResponseConstructorEmptyUrl() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Cannot redirect to an empty URL.'); $response = new RedirectResponse(''); } - /** - * @expectedException \InvalidArgumentException - */ public function testRedirectResponseConstructorWrongStatusCode() { + $this->expectException('InvalidArgumentException'); $response = new RedirectResponse('foo.bar', 404); } @@ -66,11 +65,9 @@ class RedirectResponseTest extends TestCase $this->assertEquals('baz.beep', $response->getTargetUrl()); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetTargetUrlNull() { + $this->expectException('InvalidArgumentException'); $response = new RedirectResponse('foo.bar'); $response->setTargetUrl(null); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php index 6a7bd445b7..05877cd6d5 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php @@ -921,11 +921,9 @@ class RequestTest extends TestCase $this->assertEquals(80, $port, 'With only PROTO set and value is not recognized, getPort() defaults to 80.'); } - /** - * @expectedException \RuntimeException - */ public function testGetHostWithFakeHttpHostValue() { + $this->expectException('RuntimeException'); $request = new Request(); $request->initialize([], [], [], [], [], ['HTTP_HOST' => 'www.host.com?query=string']); $request->getHost(); @@ -1090,11 +1088,11 @@ class RequestTest extends TestCase } /** - * @expectedException \Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException * @dataProvider getClientIpsWithConflictingHeadersProvider */ public function testGetClientIpsWithConflictingHeaders($httpForwarded, $httpXForwardedFor) { + $this->expectException('Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException'); $request = new Request(); $server = [ diff --git a/src/Symfony/Component/HttpFoundation/Tests/ResponseHeaderBagTest.php b/src/Symfony/Component/HttpFoundation/Tests/ResponseHeaderBagTest.php index 35df36c1c6..d6638e10cb 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/ResponseHeaderBagTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/ResponseHeaderBagTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\ResponseHeaderBag; @@ -20,6 +21,8 @@ use Symfony\Component\HttpFoundation\ResponseHeaderBag; */ class ResponseHeaderBagTest extends TestCase { + use ForwardCompatTestTrait; + public function testAllPreserveCase() { $headers = [ @@ -240,11 +243,9 @@ class ResponseHeaderBagTest extends TestCase $this->assertEquals([], $bag->getCookies()); } - /** - * @expectedException \InvalidArgumentException - */ public function testGetCookiesWithInvalidArgument() { + $this->expectException('InvalidArgumentException'); $bag = new ResponseHeaderBag(); $bag->getCookies('invalid_argument'); diff --git a/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php b/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php index 550d7ce0b0..4edada1160 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\HttpFoundation\Tests; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -20,6 +21,8 @@ use Symfony\Component\HttpFoundation\Response; */ class ResponseTest extends ResponseTestCase { + use ForwardCompatTestTrait; + public function testCreate() { $response = Response::create('foo', 301, ['Foo' => 'bar']); @@ -902,11 +905,11 @@ class ResponseTest extends ResponseTestCase } /** - * @expectedException \UnexpectedValueException * @dataProvider invalidContentProvider */ public function testSetContentInvalid($content) { + $this->expectException('UnexpectedValueException'); $response = new Response(); $response->setContent($content); } @@ -991,11 +994,11 @@ class ResponseTest extends ResponseTestCase } /** - * @see http://github.com/zendframework/zend-diactoros for the canonical source repository + * @see http://github.com/zendframework/zend-diactoros for the canonical source repository * - * @author Fábio Pacheco + * @author Fábio Pacheco * @copyright Copyright (c) 2015-2016 Zend Technologies USA Inc. (http://www.zend.com) - * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License + * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License */ public function ianaCodesReasonPhrasesProvider() { diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php index f4e775b719..c0057dd3eb 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php @@ -55,11 +55,9 @@ class MongoDbSessionHandlerTest extends TestCase $this->storage = new MongoDbSessionHandler($this->mongo, $this->options); } - /** - * @expectedException \InvalidArgumentException - */ public function testConstructorShouldThrowExceptionForMissingOptions() { + $this->expectException('InvalidArgumentException'); new MongoDbSessionHandler($this->mongo, []); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php index e227bebf62..ad1a6adff4 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler; use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; @@ -25,6 +26,8 @@ use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; */ class NativeFileSessionHandlerTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstruct() { $storage = new NativeSessionStorage(['name' => 'TESTING'], new NativeFileSessionHandler(sys_get_temp_dir())); @@ -58,11 +61,9 @@ class NativeFileSessionHandlerTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - */ public function testConstructException() { + $this->expectException('InvalidArgumentException'); $handler = new NativeFileSessionHandler('something;invalid;with;too-many-args'); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index 23eb5b11aa..b2af73e2f4 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -51,22 +51,18 @@ class PdoSessionHandlerTest extends TestCase return $pdo; } - /** - * @expectedException \InvalidArgumentException - */ public function testWrongPdoErrMode() { + $this->expectException('InvalidArgumentException'); $pdo = $this->getMemorySqlitePdo(); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT); $storage = new PdoSessionHandler($pdo); } - /** - * @expectedException \RuntimeException - */ public function testInexistentTable() { + $this->expectException('RuntimeException'); $storage = new PdoSessionHandler($this->getMemorySqlitePdo(), ['db_table' => 'inexistent_table']); $storage->open('', 'sid'); $storage->read('id'); @@ -74,11 +70,9 @@ class PdoSessionHandlerTest extends TestCase $storage->close(); } - /** - * @expectedException \RuntimeException - */ public function testCreateTableTwice() { + $this->expectException('RuntimeException'); $storage = new PdoSessionHandler($this->getMemorySqlitePdo()); $storage->createTable(); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/MockArraySessionStorageTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/MockArraySessionStorageTest.php index c60a78910b..1285dbf1ad 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/MockArraySessionStorageTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/MockArraySessionStorageTest.php @@ -124,11 +124,9 @@ class MockArraySessionStorageTest extends TestCase $this->assertTrue($storage->isStarted()); } - /** - * @expectedException \RuntimeException - */ public function testUnstartedSave() { + $this->expectException('RuntimeException'); $this->storage->save(); } } diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/MockFileSessionStorageTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/MockFileSessionStorageTest.php index 67c47e417a..bd120723ea 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/MockFileSessionStorageTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/MockFileSessionStorageTest.php @@ -110,11 +110,9 @@ class MockFileSessionStorageTest extends TestCase $this->assertEquals('bar', $storage2->getBag('attributes')->get('foo'), 'values persist between instances'); } - /** - * @expectedException \RuntimeException - */ public function testSaveWithoutStart() { + $this->expectException('RuntimeException'); $storage1 = $this->getStorage(); $storage1->save(); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php index ba06902c58..04a86614bd 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php @@ -75,20 +75,16 @@ class NativeSessionStorageTest extends TestCase $this->assertSame($bag, $storage->getBag($bag->getName())); } - /** - * @expectedException \InvalidArgumentException - */ public function testRegisterBagException() { + $this->expectException('InvalidArgumentException'); $storage = $this->getStorage(); $storage->getBag('non_existing'); } - /** - * @expectedException \LogicException - */ public function testRegisterBagForAStartedSessionThrowsException() { + $this->expectException('LogicException'); $storage = $this->getStorage(); $storage->start(); $storage->registerBag(new AttributeBag()); @@ -206,11 +202,9 @@ class NativeSessionStorageTest extends TestCase $this->assertSame('200', ini_get('session.cache_expire')); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetSaveHandlerException() { + $this->expectException('InvalidArgumentException'); $storage = $this->getStorage(); $storage->setSaveHandler(new \stdClass()); } @@ -233,11 +227,9 @@ class NativeSessionStorageTest extends TestCase $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler()); } - /** - * @expectedException \RuntimeException - */ public function testStarted() { + $this->expectException('RuntimeException'); $storage = $this->getStorage(); $this->assertFalse($storage->getSaveHandler()->isActive()); diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/AbstractProxyTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/AbstractProxyTest.php index 499a54a8ed..dcd3003645 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/AbstractProxyTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/AbstractProxyTest.php @@ -83,10 +83,10 @@ class AbstractProxyTest extends TestCase /** * @runInSeparateProcess * @preserveGlobalState disabled - * @expectedException \LogicException */ public function testNameException() { + $this->expectException('LogicException'); session_start(); $this->proxy->setName('foo'); } @@ -106,10 +106,10 @@ class AbstractProxyTest extends TestCase /** * @runInSeparateProcess * @preserveGlobalState disabled - * @expectedException \LogicException */ public function testIdException() { + $this->expectException('LogicException'); session_start(); $this->proxy->setId('foo'); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php index 63b3c8afb3..d6459e10d6 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php @@ -28,7 +28,7 @@ class SessionHandlerProxyTest extends TestCase use ForwardCompatTestTrait; /** - * @var \PHPUnit_Framework_MockObject_Matcher + * @var \PHPUnit\Framework\MockObject\Matcher */ private $mock; diff --git a/src/Symfony/Component/HttpFoundation/Tests/StreamedResponseTest.php b/src/Symfony/Component/HttpFoundation/Tests/StreamedResponseTest.php index 62dfc9bc94..96ab63d496 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/StreamedResponseTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/StreamedResponseTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\StreamedResponse; class StreamedResponseTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $response = new StreamedResponse(function () { echo 'foo'; }, 404, ['Content-Type' => 'text/plain']); @@ -81,20 +84,16 @@ class StreamedResponseTest extends TestCase $this->assertEquals(1, $called); } - /** - * @expectedException \LogicException - */ public function testSendContentWithNonCallable() { + $this->expectException('LogicException'); $response = new StreamedResponse(null); $response->sendContent(); } - /** - * @expectedException \LogicException - */ public function testSetContent() { + $this->expectException('LogicException'); $response = new StreamedResponse(function () { echo 'foo'; }); $response->setContent('foo'); } diff --git a/src/Symfony/Component/HttpKernel/Tests/Bundle/BundleTest.php b/src/Symfony/Component/HttpKernel/Tests/Bundle/BundleTest.php index 394e7ed7c6..b0e5d0ea8a 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Bundle/BundleTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Bundle/BundleTest.php @@ -12,12 +12,15 @@ namespace Symfony\Component\HttpKernel\Tests\Bundle; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionNotValidBundle\ExtensionNotValidBundle; use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\ExtensionPresentBundle; class BundleTest extends TestCase { + use ForwardCompatTestTrait; + public function testGetContainerExtension() { $bundle = new ExtensionPresentBundle(); @@ -28,12 +31,10 @@ class BundleTest extends TestCase ); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage must implement Symfony\Component\DependencyInjection\Extension\ExtensionInterface - */ public function testGetContainerExtensionWithInvalidClass() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('must implement Symfony\Component\DependencyInjection\Extension\ExtensionInterface'); $bundle = new ExtensionNotValidBundle(); $bundle->getContainerExtension(); } diff --git a/src/Symfony/Component/HttpKernel/Tests/CacheClearer/Psr6CacheClearerTest.php b/src/Symfony/Component/HttpKernel/Tests/CacheClearer/Psr6CacheClearerTest.php index d24131dae5..d326c0f89a 100644 --- a/src/Symfony/Component/HttpKernel/Tests/CacheClearer/Psr6CacheClearerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/CacheClearer/Psr6CacheClearerTest.php @@ -13,10 +13,13 @@ namespace Symfony\Component\HttpKernel\Tests\CacheClearer; use PHPUnit\Framework\TestCase; use Psr\Cache\CacheItemPoolInterface; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpKernel\CacheClearer\Psr6CacheClearer; class Psr6CacheClearerTest extends TestCase { + use ForwardCompatTestTrait; + public function testClearPoolsInjectedInConstructor() { $pool = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock(); @@ -37,12 +40,10 @@ class Psr6CacheClearerTest extends TestCase (new Psr6CacheClearer(['pool' => $pool]))->clearPool('pool'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Cache pool not found: unknown - */ public function testClearPoolThrowsExceptionOnUnreferencedPool() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Cache pool not found: unknown'); (new Psr6CacheClearer())->clearPool('unknown'); } } diff --git a/src/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerTest.php b/src/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerTest.php index e620d6c8b4..cb4fa1aae2 100644 --- a/src/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerTest.php @@ -39,11 +39,9 @@ class CacheWarmerTest extends TestCase $this->assertFileExists(self::$cacheFile); } - /** - * @expectedException \RuntimeException - */ public function testWriteNonWritableCacheFileThrowsARuntimeException() { + $this->expectException('RuntimeException'); $nonWritableFile = '/this/file/is/very/probably/not/writable'; $warmer = new TestCacheWarmer($nonWritableFile); $warmer->warmUp(\dirname($nonWritableFile)); diff --git a/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/NotTaggedControllerValueResolverTest.php b/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/NotTaggedControllerValueResolverTest.php index bd22adde91..4f85b0f351 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/NotTaggedControllerValueResolverTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/NotTaggedControllerValueResolverTest.php @@ -53,12 +53,10 @@ class NotTaggedControllerValueResolverTest extends TestCase $this->assertFalse($resolver->supports($request, $argument)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Could not resolve argument $dummy of "App\Controller\Mine::method()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"? - */ public function testController() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Could not resolve argument $dummy of "App\Controller\Mine::method()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?'); $resolver = new NotTaggedControllerValueResolver(new ServiceLocator([])); $argument = new ArgumentMetadata('dummy', \stdClass::class, false, false, null); $request = $this->requestWithAttributes(['_controller' => 'App\\Controller\\Mine::method']); @@ -66,12 +64,10 @@ class NotTaggedControllerValueResolverTest extends TestCase $resolver->resolve($request, $argument); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Could not resolve argument $dummy of "App\Controller\Mine::method()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"? - */ public function testControllerWithATrailingBackSlash() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Could not resolve argument $dummy of "App\Controller\Mine::method()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?'); $resolver = new NotTaggedControllerValueResolver(new ServiceLocator([])); $argument = new ArgumentMetadata('dummy', \stdClass::class, false, false, null); $request = $this->requestWithAttributes(['_controller' => '\\App\\Controller\\Mine::method']); @@ -79,12 +75,10 @@ class NotTaggedControllerValueResolverTest extends TestCase $resolver->resolve($request, $argument); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Could not resolve argument $dummy of "App\Controller\Mine::method()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"? - */ public function testControllerWithMethodNameStartUppercase() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Could not resolve argument $dummy of "App\Controller\Mine::method()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?'); $resolver = new NotTaggedControllerValueResolver(new ServiceLocator([])); $argument = new ArgumentMetadata('dummy', \stdClass::class, false, false, null); $request = $this->requestWithAttributes(['_controller' => 'App\\Controller\\Mine::Method']); @@ -92,12 +86,10 @@ class NotTaggedControllerValueResolverTest extends TestCase $resolver->resolve($request, $argument); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Could not resolve argument $dummy of "App\Controller\Mine::method()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"? - */ public function testControllerNameIsAnArray() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Could not resolve argument $dummy of "App\Controller\Mine::method()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?'); $resolver = new NotTaggedControllerValueResolver(new ServiceLocator([])); $argument = new ArgumentMetadata('dummy', \stdClass::class, false, false, null); $request = $this->requestWithAttributes(['_controller' => ['App\\Controller\\Mine', 'method']]); diff --git a/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/ServiceValueResolverTest.php b/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/ServiceValueResolverTest.php index f1915961ff..4036727bce 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/ServiceValueResolverTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/ServiceValueResolverTest.php @@ -105,12 +105,10 @@ class ServiceValueResolverTest extends TestCase $this->assertYieldEquals([new DummyService()], $resolver->resolve($request, $argument)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Cannot autowire argument $dummy of "Symfony\Component\HttpKernel\Tests\Controller\ArgumentResolver\DummyController::index()": it references class "Symfony\Component\HttpKernel\Tests\Controller\ArgumentResolver\DummyService" but no such service exists. - */ public function testErrorIsTruncated() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Cannot autowire argument $dummy of "Symfony\Component\HttpKernel\Tests\Controller\ArgumentResolver\DummyController::index()": it references class "Symfony\Component\HttpKernel\Tests\Controller\ArgumentResolver\DummyService" but no such service exists.'); $container = new ContainerBuilder(); $container->addCompilerPass(new RegisterControllerArgumentLocatorsPass()); diff --git a/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolverTest.php b/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolverTest.php index 0aa9c6722a..312584624c 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolverTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolverTest.php @@ -165,11 +165,9 @@ class ArgumentResolverTest extends TestCase $this->assertEquals(['foo', 'foo', 'bar'], self::$resolver->getArguments($request, $controller)); } - /** - * @expectedException \InvalidArgumentException - */ public function testGetVariadicArgumentsWithoutArrayInRequest() { + $this->expectException('InvalidArgumentException'); $request = Request::create('/'); $request->attributes->set('foo', 'foo'); $request->attributes->set('bar', 'foo'); @@ -178,11 +176,9 @@ class ArgumentResolverTest extends TestCase self::$resolver->getArguments($request, $controller); } - /** - * @expectedException \InvalidArgumentException - */ public function testGetArgumentWithoutArray() { + $this->expectException('InvalidArgumentException'); $factory = new ArgumentMetadataFactory(); $valueResolver = $this->getMockBuilder(ArgumentValueResolverInterface::class)->getMock(); $resolver = new ArgumentResolver($factory, [$valueResolver]); @@ -197,11 +193,9 @@ class ArgumentResolverTest extends TestCase $resolver->getArguments($request, $controller); } - /** - * @expectedException \RuntimeException - */ public function testIfExceptionIsThrownWhenMissingAnArgument() { + $this->expectException('RuntimeException'); $request = Request::create('/'); $controller = [$this, 'controllerWithFoo']; @@ -258,11 +252,9 @@ class ArgumentResolverTest extends TestCase $this->assertEquals([$session], self::$resolver->getArguments($request, $controller)); } - /** - * @expectedException \RuntimeException - */ public function testGetSessionMissMatchWithInterface() { + $this->expectException('RuntimeException'); $session = $this->getMockBuilder(SessionInterface::class)->getMock(); $request = Request::create('/'); $request->setSession($session); @@ -271,11 +263,9 @@ class ArgumentResolverTest extends TestCase self::$resolver->getArguments($request, $controller); } - /** - * @expectedException \RuntimeException - */ public function testGetSessionMissMatchWithImplementation() { + $this->expectException('RuntimeException'); $session = new Session(new MockArraySessionStorage()); $request = Request::create('/'); $request->setSession($session); @@ -284,11 +274,9 @@ class ArgumentResolverTest extends TestCase self::$resolver->getArguments($request, $controller); } - /** - * @expectedException \RuntimeException - */ public function testGetSessionMissMatchOnNull() { + $this->expectException('RuntimeException'); $request = Request::create('/'); $controller = [$this, 'controllerWithExtendingSession']; diff --git a/src/Symfony/Component/HttpKernel/Tests/Controller/ContainerControllerResolverTest.php b/src/Symfony/Component/HttpKernel/Tests/Controller/ContainerControllerResolverTest.php index 5a6c9d70d0..922289e466 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Controller/ContainerControllerResolverTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Controller/ContainerControllerResolverTest.php @@ -122,14 +122,10 @@ class ContainerControllerResolverTest extends ControllerResolverTest $this->assertSame($service, $controller); } - /** - * Tests where the fallback instantiation fails due to required constructor arguments. - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Controller "Symfony\Component\HttpKernel\Tests\Controller\ControllerTestService" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"? - */ public function testExceptionWhenUsingRemovedControllerServiceWithClassNameAsName() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Controller "Symfony\Component\HttpKernel\Tests\Controller\ControllerTestService" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?'); $container = $this->getMockBuilder(Container::class)->getMock(); $container->expects($this->once()) ->method('has') @@ -150,14 +146,10 @@ class ContainerControllerResolverTest extends ControllerResolverTest $resolver->getController($request); } - /** - * Tests where the fallback instantiation fails due to non-existing class. - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Controller "app.my_controller" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"? - */ public function testExceptionWhenUsingRemovedControllerService() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Controller "app.my_controller" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?'); $container = $this->getMockBuilder(Container::class)->getMock(); $container->expects($this->once()) ->method('has') diff --git a/src/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php b/src/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php index 5b937594b3..4512a40b7c 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.php @@ -95,11 +95,9 @@ class ControllerResolverTest extends TestCase $this->assertInstanceOf(InvokableController::class, $controller); } - /** - * @expectedException \InvalidArgumentException - */ public function testGetControllerOnObjectWithoutInvokeMethod() { + $this->expectException('InvalidArgumentException'); $resolver = $this->createControllerResolver(); $request = Request::create('/'); diff --git a/src/Symfony/Component/HttpKernel/Tests/ControllerMetadata/ArgumentMetadataTest.php b/src/Symfony/Component/HttpKernel/Tests/ControllerMetadata/ArgumentMetadataTest.php index 05351445e0..fb6894bbf4 100644 --- a/src/Symfony/Component/HttpKernel/Tests/ControllerMetadata/ArgumentMetadataTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/ControllerMetadata/ArgumentMetadataTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\HttpKernel\Tests\ControllerMetadata; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; class ArgumentMetadataTest extends TestCase { + use ForwardCompatTestTrait; + public function testWithBcLayerWithDefault() { $argument = new ArgumentMetadata('foo', 'string', false, true, 'default value'); @@ -32,11 +35,9 @@ class ArgumentMetadataTest extends TestCase $this->assertSame('default value', $argument->getDefaultValue()); } - /** - * @expectedException \LogicException - */ public function testDefaultValueUnavailable() { + $this->expectException('LogicException'); $argument = new ArgumentMetadata('foo', 'string', false, false, null, false); $this->assertFalse($argument->isNullable()); diff --git a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/FragmentRendererPassTest.php b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/FragmentRendererPassTest.php index 087c666596..9b49bd2d99 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/FragmentRendererPassTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/FragmentRendererPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; @@ -22,14 +23,15 @@ use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface; class FragmentRendererPassTest extends TestCase { + use ForwardCompatTestTrait; + /** * Tests that content rendering not implementing FragmentRendererInterface * triggers an exception. - * - * @expectedException \InvalidArgumentException */ public function testContentRendererWithoutInterface() { + $this->expectException('InvalidArgumentException'); $builder = new ContainerBuilder(); $fragmentHandlerDefinition = $builder->register('fragment.handler'); $builder->register('my_content_renderer', 'Symfony\Component\DependencyInjection\Definition') diff --git a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php index 948311556c..f37a0dbbb0 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\ContainerAwareInterface; @@ -25,12 +26,12 @@ use Symfony\Component\HttpKernel\DependencyInjection\RegisterControllerArgumentL class RegisterControllerArgumentLocatorsPassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Class "Symfony\Component\HttpKernel\Tests\DependencyInjection\NotFound" used for service "foo" cannot be found. - */ + use ForwardCompatTestTrait; + public function testInvalidClass() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Class "Symfony\Component\HttpKernel\Tests\DependencyInjection\NotFound" used for service "foo" cannot be found.'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -42,12 +43,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Missing "action" attribute on tag "controller.service_arguments" {"argument":"bar"} for service "foo". - */ public function testNoAction() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Missing "action" attribute on tag "controller.service_arguments" {"argument":"bar"} for service "foo".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -59,12 +58,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Missing "argument" attribute on tag "controller.service_arguments" {"action":"fooAction"} for service "foo". - */ public function testNoArgument() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Missing "argument" attribute on tag "controller.service_arguments" {"action":"fooAction"} for service "foo".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -76,12 +73,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Missing "id" attribute on tag "controller.service_arguments" {"action":"fooAction","argument":"bar"} for service "foo". - */ public function testNoService() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Missing "id" attribute on tag "controller.service_arguments" {"action":"fooAction","argument":"bar"} for service "foo".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -93,12 +88,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid "action" attribute on tag "controller.service_arguments" for service "foo": no public "barAction()" method found on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController". - */ public function testInvalidMethod() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid "action" attribute on tag "controller.service_arguments" for service "foo": no public "barAction()" method found on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -110,12 +103,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid "controller.service_arguments" tag for service "foo": method "fooAction()" has no "baz" argument on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController". - */ public function testInvalidArgument() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid "controller.service_arguments" tag for service "foo": method "fooAction()" has no "baz" argument on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -207,12 +198,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $this->assertSame(['foo::fooAction'], array_keys($locator)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClass". Did you forget to add a use statement? - */ public function testExceptionOnNonExistentTypeHint() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClass". Did you forget to add a use statement?'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -223,12 +212,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassDifferentNamespaceController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Acme\NonExistentClass". - */ public function testExceptionOnNonExistentTypeHintDifferentNamespace() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassDifferentNamespaceController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Acme\NonExistentClass".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); diff --git a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/ResettableServicePassTest.php b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/ResettableServicePassTest.php index 9b23ad003d..5d4ce0b8c2 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/ResettableServicePassTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/ResettableServicePassTest.php @@ -3,6 +3,7 @@ namespace Symfony\Component\HttpKernel\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; @@ -14,6 +15,8 @@ use Symfony\Component\HttpKernel\Tests\Fixtures\ResettableService; class ResettableServicePassTest extends TestCase { + use ForwardCompatTestTrait; + public function testCompilerPass() { $container = new ContainerBuilder(); @@ -48,12 +51,10 @@ class ResettableServicePassTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Tag kernel.reset requires the "method" attribute to be set. - */ public function testMissingMethod() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Tag kernel.reset requires the "method" attribute to be set.'); $container = new ContainerBuilder(); $container->register(ResettableService::class) ->addTag('kernel.reset'); diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/FragmentListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/FragmentListenerTest.php index 40da65d240..c54cda1280 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/FragmentListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/FragmentListenerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests\EventListener; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\EventListener\FragmentListener; @@ -20,6 +21,8 @@ use Symfony\Component\HttpKernel\UriSigner; class FragmentListenerTest extends TestCase { + use ForwardCompatTestTrait; + public function testOnlyTriggeredOnFragmentRoute() { $request = Request::create('http://example.com/foo?_path=foo%3Dbar%26_controller%3Dfoo'); @@ -50,11 +53,9 @@ class FragmentListenerTest extends TestCase $this->assertEquals($expected, $request->attributes->all()); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException - */ public function testAccessDeniedWithNonSafeMethods() { + $this->expectException('Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException'); $request = Request::create('http://example.com/_fragment', 'POST'); $listener = new FragmentListener(new UriSigner('foo')); @@ -63,11 +64,9 @@ class FragmentListenerTest extends TestCase $listener->onKernelRequest($event); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException - */ public function testAccessDeniedWithWrongSignature() { + $this->expectException('Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException'); $request = Request::create('http://example.com/_fragment', 'GET', [], [], [], ['REMOTE_ADDR' => '10.0.0.1']); $listener = new FragmentListener(new UriSigner('foo')); diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php index a23a681e0b..75ca60e5fe 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php @@ -82,11 +82,9 @@ class RouterListenerTest extends TestCase return new RequestEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); } - /** - * @expectedException \InvalidArgumentException - */ public function testInvalidMatcher() { + $this->expectException('InvalidArgumentException'); new RouterListener(new \stdClass(), $this->requestStack); } @@ -207,11 +205,9 @@ class RouterListenerTest extends TestCase $this->assertContains('Welcome', $response->getContent()); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException - */ public function testRequestWithBadHost() { + $this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException'); $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); $request = Request::create('http://bad host %22/'); $event = new RequestEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/ValidateRequestListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/ValidateRequestListenerTest.php index 6f12720bd3..7803250501 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/ValidateRequestListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/ValidateRequestListenerTest.php @@ -29,11 +29,9 @@ class ValidateRequestListenerTest extends TestCase Request::setTrustedProxies([], -1); } - /** - * @expectedException \Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException - */ public function testListenerThrowsWhenMasterRequestHasInconsistentClientIps() { + $this->expectException('Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException'); $dispatcher = new EventDispatcher(); $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(); diff --git a/src/Symfony/Component/HttpKernel/Tests/Fragment/EsiFragmentRendererTest.php b/src/Symfony/Component/HttpKernel/Tests/Fragment/EsiFragmentRendererTest.php index d8006e1707..13bbdf8e1a 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Fragment/EsiFragmentRendererTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Fragment/EsiFragmentRendererTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests\Fragment; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Controller\ControllerReference; use Symfony\Component\HttpKernel\Fragment\EsiFragmentRenderer; @@ -20,6 +21,8 @@ use Symfony\Component\HttpKernel\UriSigner; class EsiFragmentRendererTest extends TestCase { + use ForwardCompatTestTrait; + public function testRenderFallbackToInlineStrategyIfEsiNotSupported() { $strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy(true)); @@ -65,11 +68,9 @@ class EsiFragmentRendererTest extends TestCase ); } - /** - * @expectedException \LogicException - */ public function testRenderControllerReferenceWithoutSignerThrowsException() { + $this->expectException('LogicException'); $strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy()); $request = Request::create('/'); @@ -79,11 +80,9 @@ class EsiFragmentRendererTest extends TestCase $strategy->render(new ControllerReference('main_controller'), $request); } - /** - * @expectedException \LogicException - */ public function testRenderAltControllerReferenceWithoutSignerThrowsException() { + $this->expectException('LogicException'); $strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy()); $request = Request::create('/'); diff --git a/src/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.php b/src/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.php index f8b79c725d..20ad664d0d 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.php @@ -39,31 +39,25 @@ class FragmentHandlerTest extends TestCase ; } - /** - * @expectedException \InvalidArgumentException - */ public function testRenderWhenRendererDoesNotExist() { + $this->expectException('InvalidArgumentException'); $handler = new FragmentHandler($this->requestStack); $handler->render('/', 'foo'); } - /** - * @expectedException \InvalidArgumentException - */ public function testRenderWithUnknownRenderer() { + $this->expectException('InvalidArgumentException'); $handler = $this->getHandler($this->returnValue(new Response('foo'))); $handler->render('/', 'bar'); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Error when rendering "http://localhost/" (Status code is 404). - */ public function testDeliverWithUnsuccessfulResponse() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Error when rendering "http://localhost/" (Status code is 404).'); $handler = $this->getHandler($this->returnValue(new Response('foo', 404))); $handler->render('/', 'foo'); diff --git a/src/Symfony/Component/HttpKernel/Tests/Fragment/HIncludeFragmentRendererTest.php b/src/Symfony/Component/HttpKernel/Tests/Fragment/HIncludeFragmentRendererTest.php index 1d0272d151..c6e46cf715 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Fragment/HIncludeFragmentRendererTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Fragment/HIncludeFragmentRendererTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests\Fragment; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Controller\ControllerReference; use Symfony\Component\HttpKernel\Fragment\HIncludeFragmentRenderer; @@ -21,11 +22,11 @@ use Twig\Loader\ArrayLoader; class HIncludeFragmentRendererTest extends TestCase { - /** - * @expectedException \LogicException - */ + use ForwardCompatTestTrait; + public function testRenderExceptionWhenControllerAndNoSigner() { + $this->expectException('LogicException'); $strategy = new HIncludeFragmentRenderer(); $strategy->render(new ControllerReference('main_controller', [], []), Request::create('/')); } diff --git a/src/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php b/src/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php index ce71804187..f3734ea9f7 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests\Fragment; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; @@ -25,6 +26,8 @@ use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; class InlineFragmentRendererTest extends TestCase { + use ForwardCompatTestTrait; + public function testRender() { $strategy = new InlineFragmentRenderer($this->getKernel($this->returnValue(new Response('foo')))); @@ -69,11 +72,9 @@ class InlineFragmentRendererTest extends TestCase Request::setTrustedProxies([], -1); } - /** - * @expectedException \RuntimeException - */ public function testRenderExceptionNoIgnoreErrors() { + $this->expectException('RuntimeException'); $dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock(); $dispatcher->expects($this->never())->method('dispatch'); diff --git a/src/Symfony/Component/HttpKernel/Tests/Fragment/RoutableFragmentRendererTest.php b/src/Symfony/Component/HttpKernel/Tests/Fragment/RoutableFragmentRendererTest.php index c03e8c4a92..dc4e59da83 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Fragment/RoutableFragmentRendererTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Fragment/RoutableFragmentRendererTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\HttpKernel\Tests\Fragment; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Controller\ControllerReference; class RoutableFragmentRendererTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getGenerateFragmentUriData */ @@ -56,11 +59,11 @@ class RoutableFragmentRendererTest extends TestCase } /** - * @expectedException \LogicException - * @dataProvider getGenerateFragmentUriDataWithNonScalar + * @dataProvider getGenerateFragmentUriDataWithNonScalar */ public function testGenerateFragmentUriWithNonScalar($controller) { + $this->expectException('LogicException'); $this->callGenerateFragmentUriMethod($controller, Request::create('/')); } diff --git a/src/Symfony/Component/HttpKernel/Tests/Fragment/SsiFragmentRendererTest.php b/src/Symfony/Component/HttpKernel/Tests/Fragment/SsiFragmentRendererTest.php index b2181725ed..fbf69610fb 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Fragment/SsiFragmentRendererTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Fragment/SsiFragmentRendererTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests\Fragment; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Controller\ControllerReference; use Symfony\Component\HttpKernel\Fragment\SsiFragmentRenderer; @@ -20,6 +21,8 @@ use Symfony\Component\HttpKernel\UriSigner; class SsiFragmentRendererTest extends TestCase { + use ForwardCompatTestTrait; + public function testRenderFallbackToInlineStrategyIfSsiNotSupported() { $strategy = new SsiFragmentRenderer(new Ssi(), $this->getInlineStrategy(true)); @@ -56,11 +59,9 @@ class SsiFragmentRendererTest extends TestCase ); } - /** - * @expectedException \LogicException - */ public function testRenderControllerReferenceWithoutSignerThrowsException() { + $this->expectException('LogicException'); $strategy = new SsiFragmentRenderer(new Ssi(), $this->getInlineStrategy()); $request = Request::create('/'); @@ -70,11 +71,9 @@ class SsiFragmentRendererTest extends TestCase $strategy->render(new ControllerReference('main_controller'), $request); } - /** - * @expectedException \LogicException - */ public function testRenderAltControllerReferenceWithoutSignerThrowsException() { + $this->expectException('LogicException'); $strategy = new SsiFragmentRenderer(new Ssi(), $this->getInlineStrategy()); $request = Request::create('/'); diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php index ef717c63f5..ad0152ea7c 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php @@ -12,12 +12,15 @@ namespace Symfony\Component\HttpKernel\Tests\HttpCache; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpCache\Esi; class EsiTest extends TestCase { + use ForwardCompatTestTrait; + public function testHasSurrogateEsiCapability() { $esi = new Esi(); @@ -153,11 +156,9 @@ class EsiTest extends TestCase $this->assertEquals('php cript language=php>', $response->getContent()); } - /** - * @expectedException \RuntimeException - */ public function testProcessWhenNoSrcInAnEsi() { + $this->expectException('RuntimeException'); $esi = new Esi(); $request = Request::create('/'); @@ -193,11 +194,9 @@ class EsiTest extends TestCase $this->assertEquals('foo', $esi->handle($cache, '/', '/alt', true)); } - /** - * @expectedException \RuntimeException - */ public function testHandleWhenResponseIsNot200() { + $this->expectException('RuntimeException'); $esi = new Esi(); $response = new Response('foo'); $response->setStatusCode(404); diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpCache/SsiTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpCache/SsiTest.php index 4411427028..bb1a9acb71 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpCache/SsiTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpCache/SsiTest.php @@ -12,12 +12,15 @@ namespace Symfony\Component\HttpKernel\Tests\HttpCache; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpCache\Ssi; class SsiTest extends TestCase { + use ForwardCompatTestTrait; + public function testHasSurrogateSsiCapability() { $ssi = new Ssi(); @@ -120,11 +123,9 @@ class SsiTest extends TestCase $this->assertEquals('php cript language=php>', $response->getContent()); } - /** - * @expectedException \RuntimeException - */ public function testProcessWhenNoSrcInAnSsi() { + $this->expectException('RuntimeException'); $ssi = new Ssi(); $request = Request::create('/'); @@ -160,11 +161,9 @@ class SsiTest extends TestCase $this->assertEquals('foo', $ssi->handle($cache, '/', '/alt', true)); } - /** - * @expectedException \RuntimeException - */ public function testHandleWhenResponseIsNot200() { + $this->expectException('RuntimeException'); $ssi = new Ssi(); $response = new Response('foo'); $response->setStatusCode(404); diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php index 457b525dd2..da259be2af 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\RedirectResponse; @@ -29,21 +30,19 @@ use Symfony\Component\HttpKernel\KernelEvents; class HttpKernelTest extends TestCase { - /** - * @expectedException \RuntimeException - */ + use ForwardCompatTestTrait; + public function testHandleWhenControllerThrowsAnExceptionAndCatchIsTrue() { + $this->expectException('RuntimeException'); $kernel = $this->getHttpKernel(new EventDispatcher(), function () { throw new \RuntimeException(); }); $kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, true); } - /** - * @expectedException \RuntimeException - */ public function testHandleWhenControllerThrowsAnExceptionAndCatchIsFalseAndNoListenerIsRegistered() { + $this->expectException('RuntimeException'); $kernel = $this->getHttpKernel(new EventDispatcher(), function () { throw new \RuntimeException(); }); $kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, false); @@ -158,11 +157,9 @@ class HttpKernelTest extends TestCase $this->assertEquals('hello', $kernel->handle(new Request())->getContent()); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException - */ public function testHandleWhenNoControllerIsFound() { + $this->expectException('Symfony\Component\HttpKernel\Exception\NotFoundHttpException'); $dispatcher = new EventDispatcher(); $kernel = $this->getHttpKernel($dispatcher, false); @@ -319,11 +316,9 @@ class HttpKernelTest extends TestCase $kernel->handle($request, HttpKernelInterface::MASTER_REQUEST); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException - */ public function testInconsistentClientIpsOnMasterRequests() { + $this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException'); $request = new Request(); $request->setTrustedProxies(['1.1.1.1'], Request::HEADER_X_FORWARDED_FOR | Request::HEADER_FORWARDED); $request->server->set('REMOTE_ADDR', '1.1.1.1'); diff --git a/src/Symfony/Component/HttpKernel/Tests/KernelTest.php b/src/Symfony/Component/HttpKernel/Tests/KernelTest.php index 3a0beb6a4c..91c056106a 100644 --- a/src/Symfony/Component/HttpKernel/Tests/KernelTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/KernelTest.php @@ -66,12 +66,10 @@ class KernelTest extends TestCase $this->assertNull($clone->getContainer()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The environment "test.env" contains invalid characters, it can only contain characters allowed in PHP class names. - */ public function testClassNameValidityGetter() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The environment "test.env" contains invalid characters, it can only contain characters allowed in PHP class names.'); // We check the classname that will be generated by using a $env that // contains invalid characters. $env = 'test.env'; @@ -320,35 +318,27 @@ EOF; $this->assertEquals($expected, serialize($kernel)); } - /** - * @expectedException \InvalidArgumentException - */ public function testLocateResourceThrowsExceptionWhenNameIsNotValid() { + $this->expectException('InvalidArgumentException'); $this->getKernel()->locateResource('Foo'); } - /** - * @expectedException \RuntimeException - */ public function testLocateResourceThrowsExceptionWhenNameIsUnsafe() { + $this->expectException('RuntimeException'); $this->getKernel()->locateResource('@FooBundle/../bar'); } - /** - * @expectedException \InvalidArgumentException - */ public function testLocateResourceThrowsExceptionWhenBundleDoesNotExist() { + $this->expectException('InvalidArgumentException'); $this->getKernel()->locateResource('@FooBundle/config/routing.xml'); } - /** - * @expectedException \InvalidArgumentException - */ public function testLocateResourceThrowsExceptionWhenResourceDoesNotExist() { + $this->expectException('InvalidArgumentException'); $kernel = $this->getKernel(['getBundle']); $kernel ->expects($this->once()) @@ -436,12 +426,10 @@ EOF; ); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Trying to register two bundles with the same name "DuplicateName" - */ public function testInitializeBundleThrowsExceptionWhenRegisteringTwoBundlesWithTheSameName() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Trying to register two bundles with the same name "DuplicateName"'); $fooBundle = $this->getBundle(null, null, 'FooBundle', 'DuplicateName'); $barBundle = $this->getBundle(null, null, 'BarBundle', 'DuplicateName'); diff --git a/src/Symfony/Component/HttpKernel/Tests/Log/LoggerTest.php b/src/Symfony/Component/HttpKernel/Tests/Log/LoggerTest.php index 26e9a99abd..1c8c064c3d 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Log/LoggerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Log/LoggerTest.php @@ -110,27 +110,21 @@ class LoggerTest extends TestCase $this->assertSame([], $this->getLogs()); } - /** - * @expectedException \Psr\Log\InvalidArgumentException - */ public function testThrowsOnInvalidLevel() { + $this->expectException('Psr\Log\InvalidArgumentException'); $this->logger->log('invalid level', 'Foo'); } - /** - * @expectedException \Psr\Log\InvalidArgumentException - */ public function testThrowsOnInvalidMinLevel() { + $this->expectException('Psr\Log\InvalidArgumentException'); new Logger('invalid'); } - /** - * @expectedException \Psr\Log\InvalidArgumentException - */ public function testInvalidOutput() { + $this->expectException('Psr\Log\InvalidArgumentException'); new Logger(LogLevel::DEBUG, '/'); } diff --git a/src/Symfony/Component/Intl/Tests/Collator/CollatorTest.php b/src/Symfony/Component/Intl/Tests/Collator/CollatorTest.php index 840d97532f..b0efe8ed32 100644 --- a/src/Symfony/Component/Intl/Tests/Collator/CollatorTest.php +++ b/src/Symfony/Component/Intl/Tests/Collator/CollatorTest.php @@ -11,33 +11,30 @@ namespace Symfony\Component\Intl\Tests\Collator; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Intl\Collator\Collator; use Symfony\Component\Intl\Globals\IntlGlobals; class CollatorTest extends AbstractCollatorTest { - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException - */ + use ForwardCompatTestTrait; + public function testConstructorWithUnsupportedLocale() { + $this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException'); new Collator('pt_BR'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testCompare() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $collator = $this->getCollator('en'); $collator->compare('a', 'b'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetAttribute() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $collator = $this->getCollator('en'); $collator->getAttribute(Collator::NUMERIC_COLLATION); } @@ -66,38 +63,30 @@ class CollatorTest extends AbstractCollatorTest $this->assertInstanceOf('\Symfony\Component\Intl\Collator\Collator', $collator); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetSortKey() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $collator = $this->getCollator('en'); $collator->getSortKey('Hello'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetStrength() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $collator = $this->getCollator('en'); $collator->getStrength(); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testSetAttribute() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $collator = $this->getCollator('en'); $collator->setAttribute(Collator::NUMERIC_COLLATION, Collator::ON); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testSetStrength() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $collator = $this->getCollator('en'); $collator->setStrength(Collator::PRIMARY); } diff --git a/src/Symfony/Component/Intl/Tests/CountriesTest.php b/src/Symfony/Component/Intl/Tests/CountriesTest.php index df1450f287..fec90d3fde 100644 --- a/src/Symfony/Component/Intl/Tests/CountriesTest.php +++ b/src/Symfony/Component/Intl/Tests/CountriesTest.php @@ -337,11 +337,9 @@ class CountriesTest extends ResourceBundleTestCase $this->assertNotSame($countryNameZh, $countryNameZhTw, 'zh_TW does not fall back to zh'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - */ public function testGetNameWithInvalidCountryCode() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); Countries::getName('foo'); } diff --git a/src/Symfony/Component/Intl/Tests/CurrenciesTest.php b/src/Symfony/Component/Intl/Tests/CurrenciesTest.php index 612e017b0a..f681f1c2d8 100644 --- a/src/Symfony/Component/Intl/Tests/CurrenciesTest.php +++ b/src/Symfony/Component/Intl/Tests/CurrenciesTest.php @@ -725,10 +725,10 @@ class CurrenciesTest extends ResourceBundleTestCase /** * @dataProvider provideCurrenciesWithoutNumericEquivalent - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException */ public function testGetNumericCodeFailsIfNoNumericEquivalent($currency) { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); Currencies::getNumericCode($currency); } @@ -770,18 +770,16 @@ class CurrenciesTest extends ResourceBundleTestCase /** * @dataProvider provideInvalidNumericCodes - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException */ public function testForNumericCodeFailsIfInvalidNumericCode($currency) { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); Currencies::forNumericCode($currency); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - */ public function testGetNameWithInvalidCurrencyCode() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); Currencies::getName('foo'); } diff --git a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/BundleEntryReaderTest.php b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/BundleEntryReaderTest.php index 02f9830de4..f20da714b5 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/BundleEntryReaderTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/BundleEntryReaderTest.php @@ -105,11 +105,9 @@ class BundleEntryReaderTest extends TestCase $this->assertSame('Bar', $this->reader->readEntry(self::RES_DIR, 'root', ['Entries', 'Foo'])); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - */ public function testReadNonExistingEntry() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); $this->readerImpl->expects($this->once()) ->method('read') ->with(self::RES_DIR, 'root') @@ -133,11 +131,9 @@ class BundleEntryReaderTest extends TestCase $this->assertSame('Lah', $this->reader->readEntry(self::RES_DIR, 'en_GB', ['Entries', 'Bam'])); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - */ public function testDontFallbackIfEntryDoesNotExistAndFallbackDisabled() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); $this->readerImpl->expects($this->once()) ->method('read') ->with(self::RES_DIR, 'en_GB') @@ -161,11 +157,9 @@ class BundleEntryReaderTest extends TestCase $this->assertSame('Lah', $this->reader->readEntry(self::RES_DIR, 'en_GB', ['Entries', 'Bam'])); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - */ public function testDontFallbackIfLocaleDoesNotExistAndFallbackDisabled() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); $this->readerImpl->expects($this->once()) ->method('read') ->with(self::RES_DIR, 'en_GB') @@ -293,11 +287,9 @@ class BundleEntryReaderTest extends TestCase $this->assertSame($childData, $this->reader->readEntry(self::RES_DIR, 'en_GB', ['Foo', 'Bar'], true)); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - */ public function testFailIfEntryFoundNeitherInParentNorChild() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); $this->readerImpl->expects($this->at(0)) ->method('read') ->with(self::RES_DIR, 'en_GB') diff --git a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/IntlBundleReaderTest.php b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/IntlBundleReaderTest.php index a3cc63669b..3b86afbb0f 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/IntlBundleReaderTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/IntlBundleReaderTest.php @@ -76,27 +76,21 @@ class IntlBundleReaderTest extends TestCase $this->assertArrayNotHasKey('ExistsNot', $data); } - /** - * @expectedException \Symfony\Component\Intl\Exception\ResourceBundleNotFoundException - */ public function testReadFailsIfNonExistingLocale() { + $this->expectException('Symfony\Component\Intl\Exception\ResourceBundleNotFoundException'); $this->reader->read(__DIR__.'/Fixtures/res', 'foo'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\ResourceBundleNotFoundException - */ public function testReadFailsIfNonExistingFallbackLocale() { + $this->expectException('Symfony\Component\Intl\Exception\ResourceBundleNotFoundException'); $this->reader->read(__DIR__.'/Fixtures/res', 'ro_AT'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\RuntimeException - */ public function testReadFailsIfNonExistingDirectory() { + $this->expectException('Symfony\Component\Intl\Exception\RuntimeException'); $this->reader->read(__DIR__.'/foo', 'ro'); } } diff --git a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/JsonBundleReaderTest.php b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/JsonBundleReaderTest.php index cf9dac64b5..73697f0565 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/JsonBundleReaderTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/JsonBundleReaderTest.php @@ -41,43 +41,33 @@ class JsonBundleReaderTest extends TestCase $this->assertArrayNotHasKey('ExistsNot', $data); } - /** - * @expectedException \Symfony\Component\Intl\Exception\ResourceBundleNotFoundException - */ public function testReadFailsIfNonExistingLocale() { + $this->expectException('Symfony\Component\Intl\Exception\ResourceBundleNotFoundException'); $this->reader->read(__DIR__.'/Fixtures/json', 'foo'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\RuntimeException - */ public function testReadFailsIfNonExistingDirectory() { + $this->expectException('Symfony\Component\Intl\Exception\RuntimeException'); $this->reader->read(__DIR__.'/foo', 'en'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\RuntimeException - */ public function testReadFailsIfNotAFile() { + $this->expectException('Symfony\Component\Intl\Exception\RuntimeException'); $this->reader->read(__DIR__.'/Fixtures/NotAFile', 'en'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\RuntimeException - */ public function testReadFailsIfInvalidJson() { + $this->expectException('Symfony\Component\Intl\Exception\RuntimeException'); $this->reader->read(__DIR__.'/Fixtures/json', 'en_Invalid'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\ResourceBundleNotFoundException - */ public function testReaderDoesNotBreakOutOfGivenPath() { + $this->expectException('Symfony\Component\Intl\Exception\ResourceBundleNotFoundException'); $this->reader->read(__DIR__.'/Fixtures/json', '../invalid_directory/en'); } } diff --git a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/PhpBundleReaderTest.php b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/PhpBundleReaderTest.php index d4879b9479..300f860aa1 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/PhpBundleReaderTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Bundle/Reader/PhpBundleReaderTest.php @@ -41,35 +41,27 @@ class PhpBundleReaderTest extends TestCase $this->assertArrayNotHasKey('ExistsNot', $data); } - /** - * @expectedException \Symfony\Component\Intl\Exception\ResourceBundleNotFoundException - */ public function testReadFailsIfNonExistingLocale() { + $this->expectException('Symfony\Component\Intl\Exception\ResourceBundleNotFoundException'); $this->reader->read(__DIR__.'/Fixtures/php', 'foo'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\RuntimeException - */ public function testReadFailsIfNonExistingDirectory() { + $this->expectException('Symfony\Component\Intl\Exception\RuntimeException'); $this->reader->read(__DIR__.'/foo', 'en'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\RuntimeException - */ public function testReadFailsIfNotAFile() { + $this->expectException('Symfony\Component\Intl\Exception\RuntimeException'); $this->reader->read(__DIR__.'/Fixtures/NotAFile', 'en'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\ResourceBundleNotFoundException - */ public function testReaderDoesNotBreakOutOfGivenPath() { + $this->expectException('Symfony\Component\Intl\Exception\ResourceBundleNotFoundException'); $this->reader->read(__DIR__.'/Fixtures/php', '../invalid_directory/en'); } } diff --git a/src/Symfony/Component/Intl/Tests/Data/Util/RingBufferTest.php b/src/Symfony/Component/Intl/Tests/Data/Util/RingBufferTest.php index 425c0bba04..b990a94362 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Util/RingBufferTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Util/RingBufferTest.php @@ -55,11 +55,9 @@ class RingBufferTest extends TestCase $this->assertSame('bam', $this->buffer[2]); } - /** - * @expectedException \Symfony\Component\Intl\Exception\OutOfBoundsException - */ public function testReadNonExistingFails() { + $this->expectException('Symfony\Component\Intl\Exception\OutOfBoundsException'); $this->buffer['foo']; } @@ -75,11 +73,9 @@ class RingBufferTest extends TestCase $this->assertArrayNotHasKey('foo', $this->buffer); } - /** - * @expectedException \Symfony\Component\Intl\Exception\OutOfBoundsException - */ public function testReadOverwrittenFails() { + $this->expectException('Symfony\Component\Intl\Exception\OutOfBoundsException'); $this->buffer[0] = 'foo'; $this->buffer['bar'] = 'baz'; $this->buffer[2] = 'bam'; diff --git a/src/Symfony/Component/Intl/Tests/DateFormatter/IntlDateFormatterTest.php b/src/Symfony/Component/Intl/Tests/DateFormatter/IntlDateFormatterTest.php index cda1935eb5..f40ee04ed5 100644 --- a/src/Symfony/Component/Intl/Tests/DateFormatter/IntlDateFormatterTest.php +++ b/src/Symfony/Component/Intl/Tests/DateFormatter/IntlDateFormatterTest.php @@ -11,11 +11,14 @@ namespace Symfony\Component\Intl\Tests\DateFormatter; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Intl\DateFormatter\IntlDateFormatter; use Symfony\Component\Intl\Globals\IntlGlobals; class IntlDateFormatterTest extends AbstractIntlDateFormatterTest { + use ForwardCompatTestTrait; + public function testConstructor() { $formatter = new IntlDateFormatter('en', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT, 'UTC', IntlDateFormatter::GREGORIAN, 'y-M-d'); @@ -34,11 +37,9 @@ class IntlDateFormatterTest extends AbstractIntlDateFormatterTest $this->assertEquals('y-M-d', $formatter->getPattern()); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException - */ public function testConstructorWithUnsupportedLocale() { + $this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException'); new IntlDateFormatter('pt_BR', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT); } @@ -73,21 +74,17 @@ class IntlDateFormatterTest extends AbstractIntlDateFormatterTest } } - /** - * @expectedException \Symfony\Component\Intl\Exception\NotImplementedException - */ public function testFormatWithUnimplementedChars() { + $this->expectException('Symfony\Component\Intl\Exception\NotImplementedException'); $pattern = 'Y'; $formatter = new IntlDateFormatter('en', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT, 'UTC', IntlDateFormatter::GREGORIAN, $pattern); $formatter->format(0); } - /** - * @expectedException \Symfony\Component\Intl\Exception\NotImplementedException - */ public function testFormatWithNonIntegerTimestamp() { + $this->expectException('Symfony\Component\Intl\Exception\NotImplementedException'); $formatter = $this->getDefaultDateFormatter(); $formatter->format([]); } @@ -110,56 +107,44 @@ class IntlDateFormatterTest extends AbstractIntlDateFormatterTest $this->assertFalse($formatter->isLenient()); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testLocaltime() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $formatter = $this->getDefaultDateFormatter(); $formatter->localtime('Wednesday, December 31, 1969 4:00:00 PM PT'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodArgumentNotImplementedException - */ public function testParseWithNotNullPositionValue() { + $this->expectException('Symfony\Component\Intl\Exception\MethodArgumentNotImplementedException'); $position = 0; $formatter = $this->getDefaultDateFormatter('y'); $this->assertSame(0, $formatter->parse('1970', $position)); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testSetCalendar() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $formatter = $this->getDefaultDateFormatter(); $formatter->setCalendar(IntlDateFormatter::GREGORIAN); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException - */ public function testSetLenient() { + $this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException'); $formatter = $this->getDefaultDateFormatter(); $formatter->setLenient(true); } - /** - * @expectedException \Symfony\Component\Intl\Exception\NotImplementedException - */ public function testFormatWithGmtTimeZoneAndMinutesOffset() { + $this->expectException('Symfony\Component\Intl\Exception\NotImplementedException'); parent::testFormatWithGmtTimeZoneAndMinutesOffset(); } - /** - * @expectedException \Symfony\Component\Intl\Exception\NotImplementedException - */ public function testFormatWithNonStandardTimezone() { + $this->expectException('Symfony\Component\Intl\Exception\NotImplementedException'); parent::testFormatWithNonStandardTimezone(); } diff --git a/src/Symfony/Component/Intl/Tests/LanguagesTest.php b/src/Symfony/Component/Intl/Tests/LanguagesTest.php index b87ea9a38d..5da1060cc3 100644 --- a/src/Symfony/Component/Intl/Tests/LanguagesTest.php +++ b/src/Symfony/Component/Intl/Tests/LanguagesTest.php @@ -907,18 +907,16 @@ class LanguagesTest extends ResourceBundleTestCase /** * @dataProvider provideLanguagesWithoutAlpha3Equivalent - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException */ public function testGetAlpha3CodeFailsIfNoAlpha3Equivalent($language) { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); Languages::getAlpha3Code($language); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - */ public function testGetNameWithInvalidLanguageCode() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); Languages::getName('foo'); } diff --git a/src/Symfony/Component/Intl/Tests/Locale/LocaleTest.php b/src/Symfony/Component/Intl/Tests/Locale/LocaleTest.php index e7bdb7102a..e5d547294b 100644 --- a/src/Symfony/Component/Intl/Tests/Locale/LocaleTest.php +++ b/src/Symfony/Component/Intl/Tests/Locale/LocaleTest.php @@ -11,15 +11,16 @@ namespace Symfony\Component\Intl\Tests\Locale; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Intl\Locale\Locale; class LocaleTest extends AbstractLocaleTest { - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ + use ForwardCompatTestTrait; + public function testAcceptFromHttp() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('acceptFromHttp', 'pt-br,en-us;q=0.7,en;q=0.5'); } @@ -34,11 +35,9 @@ class LocaleTest extends AbstractLocaleTest $this->assertSame('123', $this->call('canonicalize', 123)); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testComposeLocale() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $subtags = [ 'language' => 'pt', 'script' => 'Latn', @@ -47,99 +46,75 @@ class LocaleTest extends AbstractLocaleTest $this->call('composeLocale', $subtags); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testFilterMatches() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('filterMatches', 'pt-BR', 'pt-BR'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetAllVariants() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('getAllVariants', 'pt_BR_Latn'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetDisplayLanguage() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('getDisplayLanguage', 'pt-Latn-BR', 'en'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetDisplayName() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('getDisplayName', 'pt-Latn-BR', 'en'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetDisplayRegion() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('getDisplayRegion', 'pt-Latn-BR', 'en'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetDisplayScript() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('getDisplayScript', 'pt-Latn-BR', 'en'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetDisplayVariant() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('getDisplayVariant', 'pt-Latn-BR', 'en'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetKeywords() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('getKeywords', 'pt-BR@currency=BRL'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetPrimaryLanguage() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('getPrimaryLanguage', 'pt-Latn-BR'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetRegion() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('getRegion', 'pt-Latn-BR'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetScript() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('getScript', 'pt-Latn-BR'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testLookup() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $langtag = [ 'pt-Latn-BR', 'pt-BR', @@ -147,19 +122,15 @@ class LocaleTest extends AbstractLocaleTest $this->call('lookup', $langtag, 'pt-BR-x-priv1'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testParseLocale() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('parseLocale', 'pt-Latn-BR'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testSetDefault() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $this->call('setDefault', 'pt_BR'); } diff --git a/src/Symfony/Component/Intl/Tests/LocalesTest.php b/src/Symfony/Component/Intl/Tests/LocalesTest.php index 5ccff4923f..3265c723d1 100644 --- a/src/Symfony/Component/Intl/Tests/LocalesTest.php +++ b/src/Symfony/Component/Intl/Tests/LocalesTest.php @@ -84,11 +84,9 @@ class LocalesTest extends ResourceBundleTestCase } } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - */ public function testGetNameWithInvalidLocale() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); Locales::getName('foo'); } diff --git a/src/Symfony/Component/Intl/Tests/NumberFormatter/NumberFormatterTest.php b/src/Symfony/Component/Intl/Tests/NumberFormatter/NumberFormatterTest.php index c5c047642d..28bf9f5473 100644 --- a/src/Symfony/Component/Intl/Tests/NumberFormatter/NumberFormatterTest.php +++ b/src/Symfony/Component/Intl/Tests/NumberFormatter/NumberFormatterTest.php @@ -23,44 +23,34 @@ class NumberFormatterTest extends AbstractNumberFormatterTest { use ForwardCompatTestTrait; - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException - */ public function testConstructorWithUnsupportedLocale() { + $this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException'); new NumberFormatter('pt_BR'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException - */ public function testConstructorWithUnsupportedStyle() { + $this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException'); new NumberFormatter('en', NumberFormatter::PATTERN_DECIMAL); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodArgumentNotImplementedException - */ public function testConstructorWithPatternDifferentThanNull() { + $this->expectException('Symfony\Component\Intl\Exception\MethodArgumentNotImplementedException'); new NumberFormatter('en', NumberFormatter::DECIMAL, ''); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException - */ public function testSetAttributeWithUnsupportedAttribute() { + $this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException'); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->setAttribute(NumberFormatter::LENIENT_PARSE, null); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException - */ public function testSetAttributeInvalidRoundingMode() { + $this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException'); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->setAttribute(NumberFormatter::ROUNDING_MODE, -1); } @@ -81,73 +71,69 @@ class NumberFormatterTest extends AbstractNumberFormatterTest ); } - /** - * @expectedException \RuntimeException - */ public function testFormatWithCurrencyStyle() { + $this->expectException('RuntimeException'); parent::testFormatWithCurrencyStyle(); } /** * @dataProvider formatTypeInt32Provider - * @expectedException \Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException */ public function testFormatTypeInt32($formatter, $value, $expected, $message = '') { + $this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException'); parent::testFormatTypeInt32($formatter, $value, $expected, $message); } /** * @dataProvider formatTypeInt32WithCurrencyStyleProvider - * @expectedException \Symfony\Component\Intl\Exception\NotImplementedException */ public function testFormatTypeInt32WithCurrencyStyle($formatter, $value, $expected, $message = '') { + $this->expectException('Symfony\Component\Intl\Exception\NotImplementedException'); parent::testFormatTypeInt32WithCurrencyStyle($formatter, $value, $expected, $message); } /** * @dataProvider formatTypeInt64Provider - * @expectedException \Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException */ public function testFormatTypeInt64($formatter, $value, $expected) { + $this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException'); parent::testFormatTypeInt64($formatter, $value, $expected); } /** * @dataProvider formatTypeInt64WithCurrencyStyleProvider - * @expectedException \Symfony\Component\Intl\Exception\NotImplementedException */ public function testFormatTypeInt64WithCurrencyStyle($formatter, $value, $expected) { + $this->expectException('Symfony\Component\Intl\Exception\NotImplementedException'); parent::testFormatTypeInt64WithCurrencyStyle($formatter, $value, $expected); } /** * @dataProvider formatTypeDoubleProvider - * @expectedException \Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException */ public function testFormatTypeDouble($formatter, $value, $expected) { + $this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException'); parent::testFormatTypeDouble($formatter, $value, $expected); } /** * @dataProvider formatTypeDoubleWithCurrencyStyleProvider - * @expectedException \Symfony\Component\Intl\Exception\NotImplementedException */ public function testFormatTypeDoubleWithCurrencyStyle($formatter, $value, $expected) { + $this->expectException('Symfony\Component\Intl\Exception\NotImplementedException'); parent::testFormatTypeDoubleWithCurrencyStyle($formatter, $value, $expected); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testGetPattern() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->getPattern(); } @@ -158,38 +144,30 @@ class NumberFormatterTest extends AbstractNumberFormatterTest $this->assertEquals(IntlGlobals::U_ZERO_ERROR, $formatter->getErrorCode()); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testParseCurrency() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->parseCurrency(null, $currency); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testSetPattern() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->setPattern(null); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testSetSymbol() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->setSymbol(null, null); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException - */ public function testSetTextAttribute() { + $this->expectException('Symfony\Component\Intl\Exception\MethodNotImplementedException'); $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $formatter->setTextAttribute(null, null); } diff --git a/src/Symfony/Component/Intl/Tests/ScriptsTest.php b/src/Symfony/Component/Intl/Tests/ScriptsTest.php index bc696cf63f..4b7967f548 100644 --- a/src/Symfony/Component/Intl/Tests/ScriptsTest.php +++ b/src/Symfony/Component/Intl/Tests/ScriptsTest.php @@ -273,11 +273,9 @@ class ScriptsTest extends ResourceBundleTestCase } } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - */ public function testGetNameWithInvalidScriptCode() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); Scripts::getName('foo'); } diff --git a/src/Symfony/Component/Intl/Tests/TimezonesTest.php b/src/Symfony/Component/Intl/Tests/TimezonesTest.php index ef922e1de8..c438d32eaa 100644 --- a/src/Symfony/Component/Intl/Tests/TimezonesTest.php +++ b/src/Symfony/Component/Intl/Tests/TimezonesTest.php @@ -527,19 +527,15 @@ class TimezonesTest extends ResourceBundleTestCase } } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - */ public function testGetNameWithInvalidTimezone() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); Timezones::getName('foo'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - */ public function testGetNameWithAliasTimezone() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); Timezones::getName('US/Pacific'); // alias in icu (not compiled), name unavailable in php } @@ -561,12 +557,10 @@ class TimezonesTest extends ResourceBundleTestCase Timezones::getRawOffset('US/Pacific'); } - /** - * @expectedException \Exception - * @expectedExceptionMessage Unknown or bad timezone (foobar) - */ public function testGetRawOffsetWithUnknownTimezone() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Unknown or bad timezone (foobar)'); Timezones::getRawOffset('foobar'); } @@ -595,28 +589,22 @@ class TimezonesTest extends ResourceBundleTestCase $this->assertSame(['Europe/Berlin', 'Europe/Busingen'], Timezones::forCountryCode('DE')); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - */ public function testForCountryCodeWithUnknownCountry() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); Timezones::forCountryCode('foobar'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - * @expectedExceptionMessage Country codes must be in uppercase, but "nl" was passed. Try with "NL" country code instead. - */ public function testForCountryCodeWithWrongCountryCode() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); + $this->expectExceptionMessage('Country codes must be in uppercase, but "nl" was passed. Try with "NL" country code instead.'); Timezones::forCountryCode('nl'); } - /** - * @expectedException \Symfony\Component\Intl\Exception\MissingResourceException - */ public function testGetCountryCodeWithUnknownTimezone() { + $this->expectException('Symfony\Component\Intl\Exception\MissingResourceException'); Timezones::getCountryCode('foobar'); } diff --git a/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/EntryManagerTest.php b/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/EntryManagerTest.php index 758ae78e49..918ff9af1b 100644 --- a/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/EntryManagerTest.php +++ b/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/EntryManagerTest.php @@ -11,18 +11,19 @@ namespace Symfony\Component\Ldap\Tests\Adapter\ExtLdap; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Ldap\Adapter\ExtLdap\Connection; use Symfony\Component\Ldap\Adapter\ExtLdap\EntryManager; use Symfony\Component\Ldap\Entry; class EntryManagerTest extends TestCase { - /** - * @expectedException \Symfony\Component\Ldap\Exception\LdapException - * @expectedExceptionMessage Entry "$$$$$$" malformed, could not parse RDN. - */ + use ForwardCompatTestTrait; + public function testMove() { + $this->expectException('Symfony\Component\Ldap\Exception\LdapException'); + $this->expectExceptionMessage('Entry "$$$$$$" malformed, could not parse RDN.'); $connection = $this->createMock(Connection::class); $connection ->expects($this->once()) @@ -33,12 +34,10 @@ class EntryManagerTest extends TestCase $entryManager->move($entry, 'a'); } - /** - * @expectedException \Symfony\Component\Ldap\Exception\NotBoundException - * @expectedExceptionMessage Query execution is not possible without binding the connection first. - */ public function testGetResources() { + $this->expectException('Symfony\Component\Ldap\Exception\NotBoundException'); + $this->expectExceptionMessage('Query execution is not possible without binding the connection first.'); $connection = $this->getMockBuilder(Connection::class)->getMock(); $connection ->expects($this->once()) diff --git a/src/Symfony/Component/Lock/Tests/LockTest.php b/src/Symfony/Component/Lock/Tests/LockTest.php index 1239ddba0f..1fffe74808 100644 --- a/src/Symfony/Component/Lock/Tests/LockTest.php +++ b/src/Symfony/Component/Lock/Tests/LockTest.php @@ -13,6 +13,7 @@ namespace Symfony\Component\Lock\Tests; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Lock\BlockingStoreInterface; use Symfony\Component\Lock\Exception\LockConflictedException; use Symfony\Component\Lock\Key; @@ -24,6 +25,8 @@ use Symfony\Component\Lock\PersistingStoreInterface; */ class LockTest extends TestCase { + use ForwardCompatTestTrait; + public function testAcquireNoBlocking() { $key = new Key(uniqid(__METHOD__, true)); @@ -248,11 +251,9 @@ class LockTest extends TestCase unset($lock); } - /** - * @expectedException \Symfony\Component\Lock\Exception\LockReleasingException - */ public function testReleaseThrowsExceptionWhenDeletionFail() { + $this->expectException('Symfony\Component\Lock\Exception\LockReleasingException'); $key = new Key(uniqid(__METHOD__, true)); $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); $lock = new Lock($key, $store, 10); @@ -271,11 +272,9 @@ class LockTest extends TestCase $lock->release(); } - /** - * @expectedException \Symfony\Component\Lock\Exception\LockReleasingException - */ public function testReleaseThrowsExceptionIfNotWellDeleted() { + $this->expectException('Symfony\Component\Lock\Exception\LockReleasingException'); $key = new Key(uniqid(__METHOD__, true)); $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); $lock = new Lock($key, $store, 10); @@ -294,11 +293,9 @@ class LockTest extends TestCase $lock->release(); } - /** - * @expectedException \Symfony\Component\Lock\Exception\LockReleasingException - */ public function testReleaseThrowsAndLog() { + $this->expectException('Symfony\Component\Lock\Exception\LockReleasingException'); $key = new Key(uniqid(__METHOD__, true)); $store = $this->getMockBuilder(PersistingStoreInterface::class)->getMock(); $logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); diff --git a/src/Symfony/Component/Lock/Tests/Store/CombinedStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/CombinedStoreTest.php index 3cc258c3b7..7afe3e800d 100644 --- a/src/Symfony/Component/Lock/Tests/Store/CombinedStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/CombinedStoreTest.php @@ -70,11 +70,9 @@ class CombinedStoreTest extends AbstractStoreTest $this->store = new CombinedStore([$this->store1, $this->store2], $this->strategy); } - /** - * @expectedException \Symfony\Component\Lock\Exception\LockConflictedException - */ public function testSaveThrowsExceptionOnFailure() { + $this->expectException('Symfony\Component\Lock\Exception\LockConflictedException'); $key = new Key(uniqid(__METHOD__, true)); $this->store1 @@ -167,11 +165,9 @@ class CombinedStoreTest extends AbstractStoreTest } } - /** - * @expectedException \Symfony\Component\Lock\Exception\LockConflictedException - */ public function testputOffExpirationThrowsExceptionOnFailure() { + $this->expectException('Symfony\Component\Lock\Exception\LockConflictedException'); $key = new Key(uniqid(__METHOD__, true)); $ttl = random_int(1, 10); diff --git a/src/Symfony/Component/Lock/Tests/Store/ExpiringStoreTestTrait.php b/src/Symfony/Component/Lock/Tests/Store/ExpiringStoreTestTrait.php index 019b6f40de..15b7522671 100644 --- a/src/Symfony/Component/Lock/Tests/Store/ExpiringStoreTestTrait.php +++ b/src/Symfony/Component/Lock/Tests/Store/ExpiringStoreTestTrait.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Lock\Tests\Store; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Lock\Exception\LockExpiredException; use Symfony\Component\Lock\Key; use Symfony\Component\Lock\PersistingStoreInterface; @@ -57,11 +58,10 @@ trait ExpiringStoreTestTrait /** * Tests the store thrown exception when TTL expires. - * - * @expectedException \Symfony\Component\Lock\Exception\LockExpiredException */ public function testAbortAfterExpiration() { + $this->expectException('\Symfony\Component\Lock\Exception\LockExpiredException'); $key = new Key(uniqid(__METHOD__, true)); /** @var PersistingStoreInterface $store */ diff --git a/src/Symfony/Component/Lock/Tests/Store/FlockStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/FlockStoreTest.php index ef3650c312..42f88390db 100644 --- a/src/Symfony/Component/Lock/Tests/Store/FlockStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/FlockStoreTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Lock\Tests\Store; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Lock\Key; use Symfony\Component\Lock\Store\FlockStore; @@ -19,6 +20,7 @@ use Symfony\Component\Lock\Store\FlockStore; */ class FlockStoreTest extends AbstractStoreTest { + use ForwardCompatTestTrait; use BlockingStoreTestTrait; /** @@ -29,12 +31,10 @@ class FlockStoreTest extends AbstractStoreTest return new FlockStore(); } - /** - * @expectedException \Symfony\Component\Lock\Exception\InvalidArgumentException - * @expectedExceptionMessage The directory "/a/b/c/d/e" is not writable. - */ public function testConstructWhenRepositoryDoesNotExist() { + $this->expectException('Symfony\Component\Lock\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The directory "/a/b/c/d/e" is not writable.'); if (!getenv('USER') || 'root' === getenv('USER')) { $this->markTestSkipped('This test will fail if run under superuser'); } @@ -42,12 +42,10 @@ class FlockStoreTest extends AbstractStoreTest new FlockStore('/a/b/c/d/e'); } - /** - * @expectedException \Symfony\Component\Lock\Exception\InvalidArgumentException - * @expectedExceptionMessage The directory "/" is not writable. - */ public function testConstructWhenRepositoryIsNotWriteable() { + $this->expectException('Symfony\Component\Lock\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The directory "/" is not writable.'); if (!getenv('USER') || 'root' === getenv('USER')) { $this->markTestSkipped('This test will fail if run under superuser'); } diff --git a/src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php index dfc8dfba0d..8d22d1508b 100644 --- a/src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php @@ -61,11 +61,9 @@ class MemcachedStoreTest extends AbstractStoreTest $this->markTestSkipped('Memcached expects a TTL greater than 1 sec. Simulating a slow network is too hard'); } - /** - * @expectedException \Symfony\Component\Lock\Exception\InvalidTtlException - */ public function testInvalidTtl() { + $this->expectException('Symfony\Component\Lock\Exception\InvalidTtlException'); $store = $this->getStore(); $store->putOffExpiration(new Key('toto'), 0.1); } diff --git a/src/Symfony/Component/Lock/Tests/Store/PdoStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/PdoStoreTest.php index 0fb25459e0..77a97860fe 100644 --- a/src/Symfony/Component/Lock/Tests/Store/PdoStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/PdoStoreTest.php @@ -59,20 +59,16 @@ class PdoStoreTest extends AbstractStoreTest $this->markTestSkipped('Pdo expects a TTL greater than 1 sec. Simulating a slow network is too hard'); } - /** - * @expectedException \Symfony\Component\Lock\Exception\InvalidTtlException - */ public function testInvalidTtl() { + $this->expectException('Symfony\Component\Lock\Exception\InvalidTtlException'); $store = $this->getStore(); $store->putOffExpiration(new Key('toto'), 0.1); } - /** - * @expectedException \Symfony\Component\Lock\Exception\InvalidTtlException - */ public function testInvalidTtlConstruct() { + $this->expectException('Symfony\Component\Lock\Exception\InvalidTtlException'); return new PdoStore('sqlite:'.self::$dbFile, [], 0.1, 0.1); } } diff --git a/src/Symfony/Component/Lock/Tests/Store/RedisStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/RedisStoreTest.php index 17edd80fe2..e385ce523d 100644 --- a/src/Symfony/Component/Lock/Tests/Store/RedisStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/RedisStoreTest.php @@ -39,11 +39,9 @@ class RedisStoreTest extends AbstractRedisStoreTest return $redis; } - /** - * @expectedException \Symfony\Component\Lock\Exception\InvalidTtlException - */ public function testInvalidTtl() { + $this->expectException('Symfony\Component\Lock\Exception\InvalidTtlException'); new RedisStore($this->getRedisConnection(), -1); } } diff --git a/src/Symfony/Component/Mailer/Tests/Transport/Smtp/Stream/SocketStreamTest.php b/src/Symfony/Component/Mailer/Tests/Transport/Smtp/Stream/SocketStreamTest.php index b825d1d19a..ead0d7b73a 100644 --- a/src/Symfony/Component/Mailer/Tests/Transport/Smtp/Stream/SocketStreamTest.php +++ b/src/Symfony/Component/Mailer/Tests/Transport/Smtp/Stream/SocketStreamTest.php @@ -16,24 +16,20 @@ use Symfony\Component\Mailer\Transport\Smtp\Stream\SocketStream; class SocketStreamTest extends TestCase { - /** - * @expectedException \Symfony\Component\Mailer\Exception\TransportException - * @expectedExceptionMessageRegExp /Connection refused|unable to connect/ - */ public function testSocketErrorNoConnection() { + $this->expectException('Symfony\Component\Mailer\Exception\TransportException'); + $this->expectExceptionMessageRegExp('/Connection refused|unable to connect/'); $s = new SocketStream(); $s->setTimeout(0.1); $s->setPort(9999); $s->initialize(); } - /** - * @expectedException \Symfony\Component\Mailer\Exception\TransportException - * @expectedExceptionMessageRegExp /no valid certs found cafile stream|Unable to find the socket transport "ssl"/ - */ public function testSocketErrorBeforeConnectError() { + $this->expectException('Symfony\Component\Mailer\Exception\TransportException'); + $this->expectExceptionMessageRegExp('/no valid certs found cafile stream|Unable to find the socket transport "ssl"/'); $s = new SocketStream(); $s->setStreamOptions([ 'ssl' => [ diff --git a/src/Symfony/Component/Messenger/Tests/Command/DebugCommandTest.php b/src/Symfony/Component/Messenger/Tests/Command/DebugCommandTest.php index e78b88d0fc..02812adb47 100644 --- a/src/Symfony/Component/Messenger/Tests/Command/DebugCommandTest.php +++ b/src/Symfony/Component/Messenger/Tests/Command/DebugCommandTest.php @@ -139,12 +139,10 @@ TXT ); } - /** - * @expectedException \Symfony\Component\Console\Exception\RuntimeException - * @expectedExceptionMessage Bus "unknown_bus" does not exist. Known buses are command_bus, query_bus. - */ public function testExceptionOnUnknownBusArgument() { + $this->expectException('Symfony\Component\Console\Exception\RuntimeException'); + $this->expectExceptionMessage('Bus "unknown_bus" does not exist. Known buses are command_bus, query_bus.'); $command = new DebugCommand(['command_bus' => [], 'query_bus' => []]); $tester = new CommandTester($command); diff --git a/src/Symfony/Component/Messenger/Tests/Command/SetupTransportsCommandTest.php b/src/Symfony/Component/Messenger/Tests/Command/SetupTransportsCommandTest.php index 48df2782bd..6916d5552c 100644 --- a/src/Symfony/Component/Messenger/Tests/Command/SetupTransportsCommandTest.php +++ b/src/Symfony/Component/Messenger/Tests/Command/SetupTransportsCommandTest.php @@ -69,12 +69,10 @@ class SetupTransportsCommandTest extends TestCase $this->assertContains('The "amqp" transport was setup successfully.', $display); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage The "not_found" transport does not exist. - */ public function testReceiverNameArgumentNotFound() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('The "not_found" transport does not exist.'); // mock a service locator /** @var MockObject|ServiceLocator $serviceLocator */ $serviceLocator = $this->createMock(ServiceLocator::class); diff --git a/src/Symfony/Component/Messenger/Tests/DependencyInjection/MessengerPassTest.php b/src/Symfony/Component/Messenger/Tests/DependencyInjection/MessengerPassTest.php index 87ec875cb3..c50a70ea77 100644 --- a/src/Symfony/Component/Messenger/Tests/DependencyInjection/MessengerPassTest.php +++ b/src/Symfony/Component/Messenger/Tests/DependencyInjection/MessengerPassTest.php @@ -134,12 +134,10 @@ class MessengerPassTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid handler service "Symfony\Component\Messenger\Tests\Fixtures\DummyCommandHandler": bus "unknown_bus" specified on the tag "messenger.message_handler" does not exist (known ones are: command_bus). - */ public function testProcessTagWithUnknownBus() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\Fixtures\DummyCommandHandler": bus "unknown_bus" specified on the tag "messenger.message_handler" does not exist (known ones are: command_bus).'); $container = $this->getContainerBuilder($commandBusId = 'command_bus'); $container->register(DummyCommandHandler::class)->addTag('messenger.message_handler', ['bus' => 'unknown_bus']); @@ -208,12 +206,10 @@ class MessengerPassTest extends TestCase $this->assertSame(PrioritizedHandler::class, $secondHandlerDefinition->getClass()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid service "NonExistentHandlerClass": class "NonExistentHandlerClass" does not exist. - */ public function testThrowsExceptionIfTheHandlerClassDoesNotExist() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid service "NonExistentHandlerClass": class "NonExistentHandlerClass" does not exist.'); $container = $this->getContainerBuilder(); $container->register('message_bus', MessageBusInterface::class)->addTag('messenger.bus'); $container @@ -224,12 +220,10 @@ class MessengerPassTest extends TestCase (new MessengerPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\HandlerMappingWithNonExistentMethod": method "Symfony\Component\Messenger\Tests\DependencyInjection\HandlerMappingWithNonExistentMethod::dummyMethod()" does not exist. - */ public function testThrowsExceptionIfTheHandlerMethodDoesNotExist() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\HandlerMappingWithNonExistentMethod": method "Symfony\Component\Messenger\Tests\DependencyInjection\HandlerMappingWithNonExistentMethod::dummyMethod()" does not exist.'); $container = $this->getContainerBuilder(); $container->register('message_bus', MessageBusInterface::class)->addTag('messenger.bus'); $container @@ -357,12 +351,10 @@ class MessengerPassTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid configuration returned by method "Symfony\Component\Messenger\Tests\DependencyInjection\HandlerOnUndefinedBus::getHandledMessages()" for message "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage": bus "some_undefined_bus" does not exist. - */ public function testItThrowsAnExceptionOnUnknownBus() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid configuration returned by method "Symfony\Component\Messenger\Tests\DependencyInjection\HandlerOnUndefinedBus::getHandledMessages()" for message "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage": bus "some_undefined_bus" does not exist.'); $container = $this->getContainerBuilder(); $container ->register(HandlerOnUndefinedBus::class, HandlerOnUndefinedBus::class) @@ -372,12 +364,10 @@ class MessengerPassTest extends TestCase (new MessengerPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandler": class or interface "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessage" used as argument type in method "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandler::__invoke()" not found. - */ public function testUndefinedMessageClassForHandler() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandler": class or interface "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessage" used as argument type in method "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandler::__invoke()" not found.'); $container = $this->getContainerBuilder(); $container ->register(UndefinedMessageHandler::class, UndefinedMessageHandler::class) @@ -387,12 +377,10 @@ class MessengerPassTest extends TestCase (new MessengerPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandlerViaHandlerInterface": class or interface "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessage" used as argument type in method "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandlerViaHandlerInterface::__invoke()" not found. - */ public function testUndefinedMessageClassForHandlerImplementingMessageHandlerInterface() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandlerViaHandlerInterface": class or interface "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessage" used as argument type in method "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandlerViaHandlerInterface::__invoke()" not found.'); $container = $this->getContainerBuilder(); $container ->register(UndefinedMessageHandlerViaHandlerInterface::class, UndefinedMessageHandlerViaHandlerInterface::class) @@ -402,12 +390,10 @@ class MessengerPassTest extends TestCase (new MessengerPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandlerViaSubscriberInterface": class or interface "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessage" returned by method "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandlerViaSubscriberInterface::getHandledMessages()" not found. - */ public function testUndefinedMessageClassForHandlerImplementingMessageSubscriberInterface() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandlerViaSubscriberInterface": class or interface "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessage" returned by method "Symfony\Component\Messenger\Tests\DependencyInjection\UndefinedMessageHandlerViaSubscriberInterface::getHandledMessages()" not found.'); $container = $this->getContainerBuilder(); $container ->register(UndefinedMessageHandlerViaSubscriberInterface::class, UndefinedMessageHandlerViaSubscriberInterface::class) @@ -417,12 +403,10 @@ class MessengerPassTest extends TestCase (new MessengerPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\NotInvokableHandler": class "Symfony\Component\Messenger\Tests\DependencyInjection\NotInvokableHandler" must have an "__invoke()" method. - */ public function testNotInvokableHandler() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\NotInvokableHandler": class "Symfony\Component\Messenger\Tests\DependencyInjection\NotInvokableHandler" must have an "__invoke()" method.'); $container = $this->getContainerBuilder(); $container ->register(NotInvokableHandler::class, NotInvokableHandler::class) @@ -432,12 +416,10 @@ class MessengerPassTest extends TestCase (new MessengerPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\MissingArgumentHandler": method "Symfony\Component\Messenger\Tests\DependencyInjection\MissingArgumentHandler::__invoke()" requires at least one argument, first one being the message it handles. - */ public function testMissingArgumentHandler() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\MissingArgumentHandler": method "Symfony\Component\Messenger\Tests\DependencyInjection\MissingArgumentHandler::__invoke()" requires at least one argument, first one being the message it handles.'); $container = $this->getContainerBuilder(); $container ->register(MissingArgumentHandler::class, MissingArgumentHandler::class) @@ -447,12 +429,10 @@ class MessengerPassTest extends TestCase (new MessengerPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\MissingArgumentTypeHandler": argument "$message" of method "Symfony\Component\Messenger\Tests\DependencyInjection\MissingArgumentTypeHandler::__invoke()" must have a type-hint corresponding to the message class it handles. - */ public function testMissingArgumentTypeHandler() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\MissingArgumentTypeHandler": argument "$message" of method "Symfony\Component\Messenger\Tests\DependencyInjection\MissingArgumentTypeHandler::__invoke()" must have a type-hint corresponding to the message class it handles.'); $container = $this->getContainerBuilder(); $container ->register(MissingArgumentTypeHandler::class, MissingArgumentTypeHandler::class) @@ -462,12 +442,10 @@ class MessengerPassTest extends TestCase (new MessengerPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\BuiltinArgumentTypeHandler": type-hint of argument "$message" in method "Symfony\Component\Messenger\Tests\DependencyInjection\BuiltinArgumentTypeHandler::__invoke()" must be a class , "string" given. - */ public function testBuiltinArgumentTypeHandler() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\BuiltinArgumentTypeHandler": type-hint of argument "$message" in method "Symfony\Component\Messenger\Tests\DependencyInjection\BuiltinArgumentTypeHandler::__invoke()" must be a class , "string" given.'); $container = $this->getContainerBuilder(); $container ->register(BuiltinArgumentTypeHandler::class, BuiltinArgumentTypeHandler::class) @@ -477,12 +455,10 @@ class MessengerPassTest extends TestCase (new MessengerPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\HandleNoMessageHandler": method "Symfony\Component\Messenger\Tests\DependencyInjection\HandleNoMessageHandler::getHandledMessages()" must return one or more messages. - */ public function testNeedsToHandleAtLeastOneMessage() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid handler service "Symfony\Component\Messenger\Tests\DependencyInjection\HandleNoMessageHandler": method "Symfony\Component\Messenger\Tests\DependencyInjection\HandleNoMessageHandler::getHandledMessages()" must return one or more messages.'); $container = $this->getContainerBuilder(); $container ->register(HandleNoMessageHandler::class, HandleNoMessageHandler::class) @@ -543,12 +519,10 @@ class MessengerPassTest extends TestCase $this->assertFalse($container->hasParameter($middlewareParameter)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid middleware: service "not_defined_middleware" not found. - */ public function testCannotRegistersAnUndefinedMiddleware() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid middleware: service "not_defined_middleware" not found.'); $container = $this->getContainerBuilder($fooBusId = 'messenger.bus.foo'); $container->setParameter($middlewareParameter = $fooBusId.'.middleware', [ ['id' => 'not_defined_middleware', 'arguments' => []], @@ -557,12 +531,10 @@ class MessengerPassTest extends TestCase (new MessengerPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid middleware factory "not_an_abstract_definition": a middleware factory must be an abstract definition. - */ public function testMiddlewareFactoryDefinitionMustBeAbstract() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid middleware factory "not_an_abstract_definition": a middleware factory must be an abstract definition.'); $container = $this->getContainerBuilder($fooBusId = 'messenger.bus.foo'); $container->register('not_an_abstract_definition', UselessMiddleware::class); $container->setParameter($middlewareParameter = $fooBusId.'.middleware', [ diff --git a/src/Symfony/Component/Messenger/Tests/HandleTraitTest.php b/src/Symfony/Component/Messenger/Tests/HandleTraitTest.php index 09442f2a2c..10247cf761 100644 --- a/src/Symfony/Component/Messenger/Tests/HandleTraitTest.php +++ b/src/Symfony/Component/Messenger/Tests/HandleTraitTest.php @@ -12,12 +12,10 @@ use Symfony\Component\Messenger\Tests\Fixtures\DummyMessage; class HandleTraitTest extends TestCase { - /** - * @expectedException \Symfony\Component\Messenger\Exception\LogicException - * @expectedExceptionMessage You must provide a "Symfony\Component\Messenger\MessageBusInterface" instance in the "Symfony\Component\Messenger\Tests\TestQueryBus::$messageBus" property, "NULL" given. - */ public function testItThrowsOnNoMessageBusInstance() { + $this->expectException('Symfony\Component\Messenger\Exception\LogicException'); + $this->expectExceptionMessage('You must provide a "Symfony\Component\Messenger\MessageBusInterface" instance in the "Symfony\Component\Messenger\Tests\TestQueryBus::$messageBus" property, "NULL" given.'); $queryBus = new TestQueryBus(null); $query = new DummyMessage('Hello'); @@ -48,12 +46,10 @@ class HandleTraitTest extends TestCase $this->assertSame('result', $queryBus->query($envelope)); } - /** - * @expectedException \Symfony\Component\Messenger\Exception\LogicException - * @expectedExceptionMessage Message of type "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage" was handled zero times. Exactly one handler is expected when using "Symfony\Component\Messenger\Tests\TestQueryBus::handle()". - */ public function testHandleThrowsOnNoHandledStamp() { + $this->expectException('Symfony\Component\Messenger\Exception\LogicException'); + $this->expectExceptionMessage('Message of type "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage" was handled zero times. Exactly one handler is expected when using "Symfony\Component\Messenger\Tests\TestQueryBus::handle()".'); $bus = $this->createMock(MessageBus::class); $queryBus = new TestQueryBus($bus); @@ -63,12 +59,10 @@ class HandleTraitTest extends TestCase $queryBus->query($query); } - /** - * @expectedException \Symfony\Component\Messenger\Exception\LogicException - * @expectedExceptionMessage Message of type "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage" was handled multiple times. Only one handler is expected when using "Symfony\Component\Messenger\Tests\TestQueryBus::handle()", got 2: "FirstDummyHandler::__invoke", "SecondDummyHandler::__invoke". - */ public function testHandleThrowsOnMultipleHandledStamps() { + $this->expectException('Symfony\Component\Messenger\Exception\LogicException'); + $this->expectExceptionMessage('Message of type "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage" was handled multiple times. Only one handler is expected when using "Symfony\Component\Messenger\Tests\TestQueryBus::handle()", got 2: "FirstDummyHandler::__invoke", "SecondDummyHandler::__invoke".'); $bus = $this->createMock(MessageBus::class); $queryBus = new TestQueryBus($bus); diff --git a/src/Symfony/Component/Messenger/Tests/MessageBusTest.php b/src/Symfony/Component/Messenger/Tests/MessageBusTest.php index c8644623b7..e47b57c104 100644 --- a/src/Symfony/Component/Messenger/Tests/MessageBusTest.php +++ b/src/Symfony/Component/Messenger/Tests/MessageBusTest.php @@ -32,12 +32,10 @@ class MessageBusTest extends TestCase $this->assertInstanceOf(MessageBusInterface::class, $bus); } - /** - * @expectedException \TypeError - * @expectedExceptionMessage Invalid argument provided to "Symfony\Component\Messenger\MessageBus::dispatch()": expected object, but got string. - */ public function testItDispatchInvalidMessageType() { + $this->expectException('TypeError'); + $this->expectExceptionMessage('Invalid argument provided to "Symfony\Component\Messenger\MessageBus::dispatch()": expected object, but got string.'); (new MessageBus())->dispatch('wrong'); } diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/HandleMessageMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/HandleMessageMiddlewareTest.php index 3bc263c74b..667f4f6961 100644 --- a/src/Symfony/Component/Messenger/Tests/Middleware/HandleMessageMiddlewareTest.php +++ b/src/Symfony/Component/Messenger/Tests/Middleware/HandleMessageMiddlewareTest.php @@ -113,12 +113,10 @@ class HandleMessageMiddlewareTest extends MiddlewareTestCase ]; } - /** - * @expectedException \Symfony\Component\Messenger\Exception\NoHandlerForMessageException - * @expectedExceptionMessage No handler for message "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage" - */ public function testThrowsNoHandlerException() { + $this->expectException('Symfony\Component\Messenger\Exception\NoHandlerForMessageException'); + $this->expectExceptionMessage('No handler for message "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage"'); $middleware = new HandleMessageMiddleware(new HandlersLocator([])); $middleware->handle(new Envelope(new DummyMessage('Hey')), new StackMiddleware()); diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/TraceableMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/TraceableMiddlewareTest.php index 9e1c1dcafb..54be577554 100644 --- a/src/Symfony/Component/Messenger/Tests/Middleware/TraceableMiddlewareTest.php +++ b/src/Symfony/Component/Messenger/Tests/Middleware/TraceableMiddlewareTest.php @@ -61,12 +61,10 @@ class TraceableMiddlewareTest extends MiddlewareTestCase $traced->handle($envelope, new StackMiddleware(new \ArrayIterator([null, $middleware]))); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Thrown from next middleware. - */ public function testHandleWithException() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Thrown from next middleware.'); $busId = 'command_bus'; $middleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock(); diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/ValidationMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/ValidationMiddlewareTest.php index 510396f0a3..dc279118ec 100644 --- a/src/Symfony/Component/Messenger/Tests/Middleware/ValidationMiddlewareTest.php +++ b/src/Symfony/Component/Messenger/Tests/Middleware/ValidationMiddlewareTest.php @@ -52,12 +52,10 @@ class ValidationMiddlewareTest extends MiddlewareTestCase (new ValidationMiddleware($validator))->handle($envelope, $this->getStackMock()); } - /** - * @expectedException \Symfony\Component\Messenger\Exception\ValidationFailedException - * @expectedExceptionMessage Message of type "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage" failed validation. - */ public function testValidationFailedException() { + $this->expectException('Symfony\Component\Messenger\Exception\ValidationFailedException'); + $this->expectExceptionMessage('Message of type "Symfony\Component\Messenger\Tests\Fixtures\DummyMessage" failed validation.'); $message = new DummyMessage('Hey'); $envelope = new Envelope($message); diff --git a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpReceiverTest.php b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpReceiverTest.php index 617250f2aa..8e0b9da29a 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpReceiverTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpReceiverTest.php @@ -45,11 +45,9 @@ class AmqpReceiverTest extends TestCase $this->assertEquals(new DummyMessage('Hi'), $actualEnvelopes[0]->getMessage()); } - /** - * @expectedException \Symfony\Component\Messenger\Exception\TransportException - */ public function testItThrowsATransportExceptionIfItCannotAcknowledgeMessage() { + $this->expectException('Symfony\Component\Messenger\Exception\TransportException'); $serializer = $this->createMock(SerializerInterface::class); $amqpEnvelope = $this->createAMQPEnvelope(); $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); @@ -61,11 +59,9 @@ class AmqpReceiverTest extends TestCase $receiver->ack(new Envelope(new \stdClass(), [new AmqpReceivedStamp($amqpEnvelope, 'queueName')])); } - /** - * @expectedException \Symfony\Component\Messenger\Exception\TransportException - */ public function testItThrowsATransportExceptionIfItCannotRejectMessage() { + $this->expectException('Symfony\Component\Messenger\Exception\TransportException'); $serializer = $this->createMock(SerializerInterface::class); $amqpEnvelope = $this->createAMQPEnvelope(); $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); diff --git a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpSenderTest.php b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpSenderTest.php index c13345f033..002e92b249 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpSenderTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpSenderTest.php @@ -102,11 +102,9 @@ class AmqpSenderTest extends TestCase $sender->send($envelope); } - /** - * @expectedException \Symfony\Component\Messenger\Exception\TransportException - */ public function testItThrowsATransportExceptionIfItCannotSendTheMessage() { + $this->expectException('Symfony\Component\Messenger\Exception\TransportException'); $envelope = new Envelope(new DummyMessage('Oy')); $encoded = ['body' => '...', 'headers' => ['type' => DummyMessage::class]]; diff --git a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/ConnectionTest.php b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/ConnectionTest.php index f51070c1d9..5d8cd58c98 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/ConnectionTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/ConnectionTest.php @@ -25,12 +25,10 @@ class ConnectionTest extends TestCase { private const DEFAULT_EXCHANGE_NAME = 'messages'; - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The given AMQP DSN "amqp://:" is invalid. - */ public function testItCannotBeConstructedWithAWrongDsn() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The given AMQP DSN "amqp://:" is invalid.'); Connection::fromDsn('amqp://:'); } @@ -421,12 +419,10 @@ class ConnectionTest extends TestCase $connection->publish('{}', [], 120000); } - /** - * @expectedException \AMQPException - * @expectedExceptionMessage Could not connect to the AMQP server. Please verify the provided DSN. ({"host":"localhost","port":5672,"vhost":"\/","login":"user","password":"********"}) - */ public function testObfuscatePasswordInDsn() { + $this->expectException('AMQPException'); + $this->expectExceptionMessage('Could not connect to the AMQP server. Please verify the provided DSN. ({"host":"localhost","port":5672,"vhost":"\/","login":"user","password":"********"})'); $factory = new TestAmqpFactory( $amqpConnection = $this->createMock(\AMQPConnection::class), $amqpChannel = $this->createMock(\AMQPChannel::class), diff --git a/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/ConnectionTest.php b/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/ConnectionTest.php index 28e54a9b36..6e7724d506 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/ConnectionTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/ConnectionTest.php @@ -78,11 +78,9 @@ class ConnectionTest extends TestCase $this->assertNull($doctrineEnvelope); } - /** - * @expectedException \Symfony\Component\Messenger\Exception\TransportException - */ public function testItThrowsATransportExceptionIfItCannotAcknowledgeMessage() { + $this->expectException('Symfony\Component\Messenger\Exception\TransportException'); $driverConnection = $this->getDBALConnectionMock(); $driverConnection->method('delete')->willThrowException(new DBALException()); @@ -90,11 +88,9 @@ class ConnectionTest extends TestCase $connection->ack('dummy_id'); } - /** - * @expectedException \Symfony\Component\Messenger\Exception\TransportException - */ public function testItThrowsATransportExceptionIfItCannotRejectMessage() { + $this->expectException('Symfony\Component\Messenger\Exception\TransportException'); $driverConnection = $this->getDBALConnectionMock(); $driverConnection->method('delete')->willThrowException(new DBALException()); @@ -240,19 +236,15 @@ class ConnectionTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\Messenger\Exception\InvalidArgumentException - */ public function testItThrowsAnExceptionIfAnExtraOptionsInDefined() { + $this->expectException('Symfony\Component\Messenger\Exception\InvalidArgumentException'); Connection::buildConfiguration('doctrine://default', ['new_option' => 'woops']); } - /** - * @expectedException \Symfony\Component\Messenger\Exception\InvalidArgumentException - */ public function testItThrowsAnExceptionIfAnExtraOptionsInDefinedInDSN() { + $this->expectException('Symfony\Component\Messenger\Exception\InvalidArgumentException'); Connection::buildConfiguration('doctrine://default?new_option=woops'); } diff --git a/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/DoctrineReceiverTest.php b/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/DoctrineReceiverTest.php index c4f73c94ca..c284c2536b 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/DoctrineReceiverTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/DoctrineReceiverTest.php @@ -53,11 +53,9 @@ class DoctrineReceiverTest extends TestCase $this->assertSame(1, $transportMessageIdStamp->getId()); } - /** - * @expectedException \Symfony\Component\Messenger\Exception\MessageDecodingFailedException - */ public function testItRejectTheMessageIfThereIsAMessageDecodingFailedException() { + $this->expectException('Symfony\Component\Messenger\Exception\MessageDecodingFailedException'); $serializer = $this->createMock(PhpSerializer::class); $serializer->method('decode')->willThrowException(new MessageDecodingFailedException()); diff --git a/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/DoctrineTransportFactoryTest.php b/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/DoctrineTransportFactoryTest.php index 9c59a2a88a..20559c5352 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/DoctrineTransportFactoryTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/Doctrine/DoctrineTransportFactoryTest.php @@ -54,12 +54,10 @@ class DoctrineTransportFactoryTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\Messenger\Exception\TransportException - * @expectedExceptionMessage Could not find Doctrine connection from Messenger DSN "doctrine://default". - */ public function testCreateTransportMustThrowAnExceptionIfManagerIsNotFound() { + $this->expectException('Symfony\Component\Messenger\Exception\TransportException'); + $this->expectExceptionMessage('Could not find Doctrine connection from Messenger DSN "doctrine://default".'); $registry = $this->createMock(ConnectionRegistry::class); $registry->expects($this->once()) ->method('getConnection') diff --git a/src/Symfony/Component/Mime/Tests/Header/IdentificationHeaderTest.php b/src/Symfony/Component/Mime/Tests/Header/IdentificationHeaderTest.php index 7d94d4d19d..b7f0095d3a 100644 --- a/src/Symfony/Component/Mime/Tests/Header/IdentificationHeaderTest.php +++ b/src/Symfony/Component/Mime/Tests/Header/IdentificationHeaderTest.php @@ -99,12 +99,10 @@ class IdentificationHeaderTest extends TestCase $this->assertEquals('', $header->getBodyAsString()); } - /** - * @expectedException \Exception - * @expectedMessageException "a b c" is not valid id-left - */ public function testInvalidIdLeftThrowsException() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Email "a b c@d" does not comply with addr-spec of RFC 2822.'); $header = new IdentificationHeader('References', 'a b c@d'); } @@ -137,21 +135,17 @@ class IdentificationHeaderTest extends TestCase $this->assertEquals('', $header->getBodyAsString()); } - /** - * @expectedException \Exception - * @expectedMessageException "b c d" is not valid id-right - */ public function testInvalidIdRightThrowsException() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Email "a@b c d" does not comply with addr-spec of RFC 2822.'); $header = new IdentificationHeader('References', 'a@b c d'); } - /** - * @expectedException \Exception - * @expectedMessageException "abc" is does not contain @ - */ public function testMissingAtSignThrowsException() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Email "abc" does not comply with addr-spec of RFC 2822.'); /* -- RFC 2822, 3.6.4. msg-id = [CFWS] "<" id-left "@" id-right ">" [CFWS] */ diff --git a/src/Symfony/Component/Mime/Tests/Header/MailboxHeaderTest.php b/src/Symfony/Component/Mime/Tests/Header/MailboxHeaderTest.php index 11a7ac9c54..72f22ff980 100644 --- a/src/Symfony/Component/Mime/Tests/Header/MailboxHeaderTest.php +++ b/src/Symfony/Component/Mime/Tests/Header/MailboxHeaderTest.php @@ -59,11 +59,9 @@ class MailboxHeaderTest extends TestCase $this->assertEquals('Fabien =?'.$header->getCharset().'?Q?P=8Ftencier?= ', $header->getBodyAsString()); } - /** - * @expectedException \Symfony\Component\Mime\Exception\AddressEncoderException - */ public function testUtf8CharsInLocalPartThrows() { + $this->expectException('Symfony\Component\Mime\Exception\AddressEncoderException'); $header = new MailboxHeader('Sender', new Address('fabïen@symfony.com')); $header->getBodyAsString(); } diff --git a/src/Symfony/Component/Mime/Tests/Header/MailboxListHeaderTest.php b/src/Symfony/Component/Mime/Tests/Header/MailboxListHeaderTest.php index a2a28050f1..2eee1cfa86 100644 --- a/src/Symfony/Component/Mime/Tests/Header/MailboxListHeaderTest.php +++ b/src/Symfony/Component/Mime/Tests/Header/MailboxListHeaderTest.php @@ -56,11 +56,9 @@ class MailboxListHeaderTest extends TestCase $this->assertEquals(['Chris Corbyn '], $header->getAddressStrings()); } - /** - * @expectedException \Symfony\Component\Mime\Exception\AddressEncoderException - */ public function testUtf8CharsInLocalPartThrows() { + $this->expectException('Symfony\Component\Mime\Exception\AddressEncoderException'); $header = new MailboxListHeader('From', [new NamedAddress('chrïs@swiftmailer.org', 'Chris Corbyn')]); $header->getAddressStrings(); } diff --git a/src/Symfony/Component/Mime/Tests/Header/PathHeaderTest.php b/src/Symfony/Component/Mime/Tests/Header/PathHeaderTest.php index 8f41959944..6bc029aee4 100644 --- a/src/Symfony/Component/Mime/Tests/Header/PathHeaderTest.php +++ b/src/Symfony/Component/Mime/Tests/Header/PathHeaderTest.php @@ -23,11 +23,9 @@ class PathHeaderTest extends TestCase $this->assertEquals($address, $header->getAddress()); } - /** - * @expectedException \Exception - */ public function testAddressMustComplyWithRfc2822() { + $this->expectException('Exception'); $header = new PathHeader('Return-Path', new Address('chr is@swiftmailer.org')); } @@ -51,11 +49,9 @@ class PathHeaderTest extends TestCase $this->assertEquals('', $header->getBodyAsString()); } - /** - * @expectedException \Symfony\Component\Mime\Exception\AddressEncoderException - */ public function testAddressMustBeEncodable() { + $this->expectException('Symfony\Component\Mime\Exception\AddressEncoderException'); $header = new PathHeader('Return-Path', new Address('chrïs@swiftmailer.org')); $header->getBodyAsString(); } diff --git a/src/Symfony/Component/OptionsResolver/Tests/Debug/OptionsResolverIntrospectorTest.php b/src/Symfony/Component/OptionsResolver/Tests/Debug/OptionsResolverIntrospectorTest.php index 64a1ead1fe..fa80614d75 100644 --- a/src/Symfony/Component/OptionsResolver/Tests/Debug/OptionsResolverIntrospectorTest.php +++ b/src/Symfony/Component/OptionsResolver/Tests/Debug/OptionsResolverIntrospectorTest.php @@ -12,12 +12,15 @@ namespace Symfony\Component\OptionsResolver\Tests\Debug; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\OptionsResolver\Debug\OptionsResolverIntrospector; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class OptionsResolverIntrospectorTest extends TestCase { + use ForwardCompatTestTrait; + public function testGetDefault() { $resolver = new OptionsResolver(); @@ -36,12 +39,10 @@ class OptionsResolverIntrospectorTest extends TestCase $this->assertNull($debug->getDefault($option)); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\NoConfigurationException - * @expectedExceptionMessage No default value was set for the "foo" option. - */ public function testGetDefaultThrowsOnNoConfiguredValue() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\NoConfigurationException'); + $this->expectExceptionMessage('No default value was set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined($option = 'foo'); @@ -49,12 +50,10 @@ class OptionsResolverIntrospectorTest extends TestCase $this->assertSame('bar', $debug->getDefault($option)); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - * @expectedExceptionMessage The option "foo" does not exist. - */ public function testGetDefaultThrowsOnNotDefinedOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); + $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); $debug = new OptionsResolverIntrospector($resolver); @@ -71,12 +70,10 @@ class OptionsResolverIntrospectorTest extends TestCase $this->assertSame($closures, $debug->getLazyClosures($option)); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\NoConfigurationException - * @expectedExceptionMessage No lazy closures were set for the "foo" option. - */ public function testGetLazyClosuresThrowsOnNoConfiguredValue() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\NoConfigurationException'); + $this->expectExceptionMessage('No lazy closures were set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined($option = 'foo'); @@ -84,12 +81,10 @@ class OptionsResolverIntrospectorTest extends TestCase $this->assertSame('bar', $debug->getLazyClosures($option)); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - * @expectedExceptionMessage The option "foo" does not exist. - */ public function testGetLazyClosuresThrowsOnNotDefinedOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); + $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); $debug = new OptionsResolverIntrospector($resolver); @@ -106,12 +101,10 @@ class OptionsResolverIntrospectorTest extends TestCase $this->assertSame($allowedTypes, $debug->getAllowedTypes($option)); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\NoConfigurationException - * @expectedExceptionMessage No allowed types were set for the "foo" option. - */ public function testGetAllowedTypesThrowsOnNoConfiguredValue() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\NoConfigurationException'); + $this->expectExceptionMessage('No allowed types were set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined($option = 'foo'); @@ -119,12 +112,10 @@ class OptionsResolverIntrospectorTest extends TestCase $this->assertSame('bar', $debug->getAllowedTypes($option)); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - * @expectedExceptionMessage The option "foo" does not exist. - */ public function testGetAllowedTypesThrowsOnNotDefinedOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); + $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); $debug = new OptionsResolverIntrospector($resolver); @@ -141,12 +132,10 @@ class OptionsResolverIntrospectorTest extends TestCase $this->assertSame($allowedValues, $debug->getAllowedValues($option)); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\NoConfigurationException - * @expectedExceptionMessage No allowed values were set for the "foo" option. - */ public function testGetAllowedValuesThrowsOnNoConfiguredValue() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\NoConfigurationException'); + $this->expectExceptionMessage('No allowed values were set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined($option = 'foo'); @@ -154,12 +143,10 @@ class OptionsResolverIntrospectorTest extends TestCase $this->assertSame('bar', $debug->getAllowedValues($option)); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - * @expectedExceptionMessage The option "foo" does not exist. - */ public function testGetAllowedValuesThrowsOnNotDefinedOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); + $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); $debug = new OptionsResolverIntrospector($resolver); @@ -176,12 +163,10 @@ class OptionsResolverIntrospectorTest extends TestCase $this->assertSame($normalizer, $debug->getNormalizer($option)); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\NoConfigurationException - * @expectedExceptionMessage No normalizer was set for the "foo" option. - */ public function testGetNormalizerThrowsOnNoConfiguredValue() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\NoConfigurationException'); + $this->expectExceptionMessage('No normalizer was set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined($option = 'foo'); @@ -189,12 +174,10 @@ class OptionsResolverIntrospectorTest extends TestCase $this->assertSame('bar', $debug->getNormalizer($option)); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - * @expectedExceptionMessage The option "foo" does not exist. - */ public function testGetNormalizerThrowsOnNotDefinedOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); + $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); $debug = new OptionsResolverIntrospector($resolver); @@ -212,12 +195,10 @@ class OptionsResolverIntrospectorTest extends TestCase $this->assertSame([$normalizer1, $normalizer2], $debug->getNormalizers('foo')); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\NoConfigurationException - * @expectedExceptionMessage No normalizer was set for the "foo" option. - */ public function testGetNormalizersThrowsOnNoConfiguredValue() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\NoConfigurationException'); + $this->expectExceptionMessage('No normalizer was set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined('foo'); @@ -225,12 +206,10 @@ class OptionsResolverIntrospectorTest extends TestCase $debug->getNormalizers('foo'); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - * @expectedExceptionMessage The option "foo" does not exist. - */ public function testGetNormalizersThrowsOnNotDefinedOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); + $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); $debug = new OptionsResolverIntrospector($resolver); @@ -257,12 +236,10 @@ class OptionsResolverIntrospectorTest extends TestCase $this->assertSame($closure, $debug->getDeprecationMessage('foo')); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\NoConfigurationException - * @expectedExceptionMessage No deprecation was set for the "foo" option. - */ public function testGetDeprecationMessageThrowsOnNoConfiguredValue() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\NoConfigurationException'); + $this->expectExceptionMessage('No deprecation was set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined('foo'); @@ -270,12 +247,10 @@ class OptionsResolverIntrospectorTest extends TestCase $this->assertSame('bar', $debug->getDeprecationMessage('foo')); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - * @expectedExceptionMessage The option "foo" does not exist. - */ public function testGetDeprecationMessageThrowsOnNotDefinedOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); + $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); $debug = new OptionsResolverIntrospector($resolver); diff --git a/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php b/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php index 239bb170e4..51f86ab97c 100644 --- a/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php +++ b/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php @@ -32,35 +32,29 @@ class OptionsResolverTest extends TestCase $this->resolver = new OptionsResolver(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - * @expectedExceptionMessage The option "foo" does not exist. Defined options are: "a", "z". - */ public function testResolveFailsIfNonExistingOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); + $this->expectExceptionMessage('The option "foo" does not exist. Defined options are: "a", "z".'); $this->resolver->setDefault('z', '1'); $this->resolver->setDefault('a', '2'); $this->resolver->resolve(['foo' => 'bar']); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - * @expectedExceptionMessage The options "baz", "foo", "ping" do not exist. Defined options are: "a", "z". - */ public function testResolveFailsIfMultipleNonExistingOptions() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); + $this->expectExceptionMessage('The options "baz", "foo", "ping" do not exist. Defined options are: "a", "z".'); $this->resolver->setDefault('z', '1'); $this->resolver->setDefault('a', '2'); $this->resolver->resolve(['ping' => 'pong', 'foo' => 'bar', 'baz' => 'bam']); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testResolveFailsFromLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('foo', function (Options $options) { $options->resolve([]); }); @@ -84,11 +78,9 @@ class OptionsResolverTest extends TestCase ], $this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testFailIfSetDefaultFromLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('lazy', function (Options $options) { $options->setDefault('default', 42); }); @@ -228,11 +220,9 @@ class OptionsResolverTest extends TestCase $this->assertSame($this->resolver, $this->resolver->setRequired('foo')); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testFailIfSetRequiredFromLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('foo', function (Options $options) { $options->setRequired('bar'); }); @@ -240,11 +230,9 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\MissingOptionsException - */ public function testResolveFailsIfRequiredOptionMissing() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\MissingOptionsException'); $this->resolver->setRequired('foo'); $this->resolver->resolve(); @@ -356,11 +344,9 @@ class OptionsResolverTest extends TestCase $this->assertSame(['bar'], $this->resolver->getMissingOptions()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testFailIfSetDefinedFromLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('foo', function (Options $options) { $options->setDefined('bar'); }); @@ -453,11 +439,9 @@ class OptionsResolverTest extends TestCase $this->assertFalse($this->resolver->isDefined('foo')); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testFailIfSetDeprecatedFromLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver ->setDefault('bar', 'baz') ->setDefault('foo', function (Options $options) { @@ -467,32 +451,26 @@ class OptionsResolverTest extends TestCase ; } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - */ public function testSetDeprecatedFailsIfUnknownOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); $this->resolver->setDeprecated('foo'); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid type for deprecation message argument, expected string or \Closure, but got "boolean". - */ public function testSetDeprecatedFailsIfInvalidDeprecationMessageType() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid type for deprecation message argument, expected string or \Closure, but got "boolean".'); $this->resolver ->setDefined('foo') ->setDeprecated('foo', true) ; } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid type for deprecation message, expected string but got "boolean", return an empty string to ignore. - */ public function testLazyDeprecationFailsIfInvalidDeprecationMessageType() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid type for deprecation message, expected string but got "boolean", return an empty string to ignore.'); $this->resolver ->setDefined('foo') ->setDeprecated('foo', function (Options $options, $value) { @@ -502,12 +480,10 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(['foo' => null]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException - * @expectedExceptionMessage The options "foo", "bar" have a cyclic dependency. - */ public function testFailsIfCyclicDependencyBetweenDeprecation() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\OptionDefinitionException'); + $this->expectExceptionMessage('The options "foo", "bar" have a cyclic dependency.'); $this->resolver ->setDefined(['foo', 'bar']) ->setDeprecated('foo', function (Options $options, $value) { @@ -773,11 +749,9 @@ class OptionsResolverTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - */ public function testSetAllowedTypesFailsIfUnknownOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); $this->resolver->setAllowedTypes('foo', 'string'); } @@ -790,11 +764,9 @@ class OptionsResolverTest extends TestCase $this->assertSame(['foo' => ['bar', 'baz']], $options); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testFailIfSetAllowedTypesFromLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('foo', function (Options $options) { $options->setAllowedTypes('bar', 'string'); }); @@ -804,36 +776,30 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value array is expected to be of type "int[]", but one of the elements is of type "DateTime[]". - */ public function testResolveFailsIfInvalidTypedArray() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value array is expected to be of type "int[]", but one of the elements is of type "DateTime[]".'); $this->resolver->setDefined('foo'); $this->resolver->setAllowedTypes('foo', 'int[]'); $this->resolver->resolve(['foo' => [new \DateTime()]]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value "bar" is expected to be of type "int[]", but is of type "string". - */ public function testResolveFailsWithNonArray() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value "bar" is expected to be of type "int[]", but is of type "string".'); $this->resolver->setDefined('foo'); $this->resolver->setAllowedTypes('foo', 'int[]'); $this->resolver->resolve(['foo' => 'bar']); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value array is expected to be of type "int[]", but one of the elements is of type "stdClass[]". - */ public function testResolveFailsIfTypedArrayContainsInvalidTypes() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value array is expected to be of type "int[]", but one of the elements is of type "stdClass[]".'); $this->resolver->setDefined('foo'); $this->resolver->setAllowedTypes('foo', 'int[]'); $values = range(1, 5); @@ -845,12 +811,10 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(['foo' => $values]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value array is expected to be of type "int[][]", but one of the elements is of type "double[][]". - */ public function testResolveFailsWithCorrectLevelsButWrongScalar() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value array is expected to be of type "int[][]", but one of the elements is of type "double[][]".'); $this->resolver->setDefined('foo'); $this->resolver->setAllowedTypes('foo', 'int[][]'); @@ -897,12 +861,10 @@ class OptionsResolverTest extends TestCase $this->assertNotEmpty($this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value 42 is expected to be of type "string" or "bool", but is of type "integer". - */ public function testResolveFailsIfInvalidTypeMultiple() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value 42 is expected to be of type "string" or "bool", but is of type "integer".'); $this->resolver->setDefault('foo', 42); $this->resolver->setAllowedTypes('foo', ['string', 'bool']); @@ -940,30 +902,24 @@ class OptionsResolverTest extends TestCase $this->assertEquals($data, $result); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testResolveFailsIfNotInstanceOfClass() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->resolver->setDefault('foo', 'bar'); $this->resolver->setAllowedTypes('foo', '\stdClass'); $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - */ public function testAddAllowedTypesFailsIfUnknownOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); $this->resolver->addAllowedTypes('foo', 'string'); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testFailIfAddAllowedTypesFromLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('foo', function (Options $options) { $options->addAllowedTypes('bar', 'string'); }); @@ -973,11 +929,9 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testResolveFailsIfInvalidAddedType() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->resolver->setDefault('foo', 42); $this->resolver->addAllowedTypes('foo', 'string'); @@ -992,11 +946,9 @@ class OptionsResolverTest extends TestCase $this->assertNotEmpty($this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testResolveFailsIfInvalidAddedTypeMultiple() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->resolver->setDefault('foo', 42); $this->resolver->addAllowedTypes('foo', ['string', 'bool']); @@ -1033,19 +985,15 @@ class OptionsResolverTest extends TestCase $this->assertNotEmpty($this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - */ public function testSetAllowedValuesFailsIfUnknownOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); $this->resolver->setAllowedValues('foo', 'bar'); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testFailIfSetAllowedValuesFromLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('foo', function (Options $options) { $options->setAllowedValues('bar', 'baz'); }); @@ -1055,35 +1003,29 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value 42 is invalid. Accepted values are: "bar". - */ public function testResolveFailsIfInvalidValue() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value 42 is invalid. Accepted values are: "bar".'); $this->resolver->setDefined('foo'); $this->resolver->setAllowedValues('foo', 'bar'); $this->resolver->resolve(['foo' => 42]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value null is invalid. Accepted values are: "bar". - */ public function testResolveFailsIfInvalidValueIsNull() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value null is invalid. Accepted values are: "bar".'); $this->resolver->setDefault('foo', null); $this->resolver->setAllowedValues('foo', 'bar'); $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testResolveFailsIfInvalidValueStrict() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->resolver->setDefault('foo', 42); $this->resolver->setAllowedValues('foo', '42'); @@ -1106,12 +1048,10 @@ class OptionsResolverTest extends TestCase $this->assertEquals(['foo' => null], $this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value 42 is invalid. Accepted values are: "bar", false, null. - */ public function testResolveFailsIfInvalidValueMultiple() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value 42 is invalid. Accepted values are: "bar", false, null.'); $this->resolver->setDefault('foo', 42); $this->resolver->setAllowedValues('foo', ['bar', false, null]); @@ -1157,11 +1097,9 @@ class OptionsResolverTest extends TestCase $this->assertSame('bar', $passedValue); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testResolveFailsIfAllClosuresReturnFalse() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->resolver->setDefault('foo', 42); $this->resolver->setAllowedValues('foo', [ function () { return false; }, @@ -1184,19 +1122,15 @@ class OptionsResolverTest extends TestCase $this->assertEquals(['foo' => 'bar'], $this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - */ public function testAddAllowedValuesFailsIfUnknownOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); $this->resolver->addAllowedValues('foo', 'bar'); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testFailIfAddAllowedValuesFromLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('foo', function (Options $options) { $options->addAllowedValues('bar', 'baz'); }); @@ -1206,11 +1140,9 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testResolveFailsIfInvalidAddedValue() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->resolver->setDefault('foo', 42); $this->resolver->addAllowedValues('foo', 'bar'); @@ -1233,11 +1165,9 @@ class OptionsResolverTest extends TestCase $this->assertEquals(['foo' => null], $this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testResolveFailsIfInvalidAddedValueMultiple() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->resolver->setDefault('foo', 42); $this->resolver->addAllowedValues('foo', ['bar', 'baz']); @@ -1270,11 +1200,9 @@ class OptionsResolverTest extends TestCase $this->assertEquals(['foo' => 'baz'], $this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testResolveFailsIfAllAddedClosuresReturnFalse() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->resolver->setDefault('foo', 42); $this->resolver->setAllowedValues('foo', function () { return false; }); $this->resolver->addAllowedValues('foo', function () { return false; }); @@ -1316,19 +1244,15 @@ class OptionsResolverTest extends TestCase $this->assertEquals(['foo' => 'normalized'], $this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - */ public function testSetNormalizerFailsIfUnknownOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); $this->resolver->setNormalizer('foo', function () {}); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testFailIfSetNormalizerFromLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('foo', function (Options $options) { $options->setNormalizer('foo', function () {}); }); @@ -1362,11 +1286,9 @@ class OptionsResolverTest extends TestCase $this->assertEquals(['foo' => 'normalized[baz]'], $resolved); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testValidateTypeBeforeNormalization() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->resolver->setDefault('foo', 'bar'); $this->resolver->setAllowedTypes('foo', 'int'); @@ -1378,11 +1300,9 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - */ public function testValidateValueBeforeNormalization() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); $this->resolver->setDefault('foo', 'bar'); $this->resolver->setAllowedValues('foo', 'baz'); @@ -1432,11 +1352,9 @@ class OptionsResolverTest extends TestCase ], $this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException - */ public function testFailIfCyclicDependencyBetweenNormalizers() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\OptionDefinitionException'); $this->resolver->setDefault('norm1', 'bar'); $this->resolver->setDefault('norm2', 'baz'); @@ -1451,11 +1369,9 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException - */ public function testFailIfCyclicDependencyBetweenNormalizerAndLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\OptionDefinitionException'); $this->resolver->setDefault('lazy', function (Options $options) { $options['norm']; }); @@ -1588,19 +1504,15 @@ class OptionsResolverTest extends TestCase $this->assertEquals(['foo' => '2nd-normalized-1st-normalized-bar'], $this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - */ public function testAddNormalizerFailsIfUnknownOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); $this->resolver->addNormalizer('foo', function () {}); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testFailIfAddNormalizerFromLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('foo', function (Options $options) { $options->addNormalizer('foo', function () {}); }); @@ -1630,11 +1542,9 @@ class OptionsResolverTest extends TestCase ], $this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testFailIfSetDefaultsFromLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('foo', function (Options $options) { $options->setDefaults(['two' => '2']); }); @@ -1711,11 +1621,9 @@ class OptionsResolverTest extends TestCase $this->assertSame(['foo' => 'bar'], $this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testFailIfRemoveFromLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('foo', function (Options $options) { $options->remove('bar'); }); @@ -1787,11 +1695,9 @@ class OptionsResolverTest extends TestCase $this->assertSame(['foo' => 'bar'], $this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testFailIfClearFromLazyption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('foo', function (Options $options) { $options->clear(); }); @@ -1846,50 +1752,40 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(['default2' => 42, 'required' => 'value']); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testArrayAccessGetFailsOutsideResolve() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('default', 0); $this->resolver['default']; } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testArrayAccessExistsFailsOutsideResolve() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('default', 0); isset($this->resolver['default']); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testArrayAccessSetNotSupported() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver['default'] = 0; } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException - */ public function testArrayAccessUnsetNotSupported() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('default', 0); unset($this->resolver['default']); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\NoSuchOptionException - * @expectedExceptionMessage The option "undefined" does not exist. Defined options are: "foo", "lazy". - */ public function testFailIfGetNonExisting() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\NoSuchOptionException'); + $this->expectExceptionMessage('The option "undefined" does not exist. Defined options are: "foo", "lazy".'); $this->resolver->setDefault('foo', 'bar'); $this->resolver->setDefault('lazy', function (Options $options) { @@ -1899,12 +1795,10 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\NoSuchOptionException - * @expectedExceptionMessage The optional option "defined" has no value set. You should make sure it is set with "isset" before reading it. - */ public function testFailIfGetDefinedButUnset() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\NoSuchOptionException'); + $this->expectExceptionMessage('The optional option "defined" has no value set. You should make sure it is set with "isset" before reading it.'); $this->resolver->setDefined('defined'); $this->resolver->setDefault('lazy', function (Options $options) { @@ -1914,11 +1808,9 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException - */ public function testFailIfCyclicDependency() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\OptionDefinitionException'); $this->resolver->setDefault('lazy1', function (Options $options) { $options['lazy2']; }); @@ -1948,11 +1840,10 @@ class OptionsResolverTest extends TestCase * In resolve() we count the options that are actually set (which may be * only a subset of the defined options). Outside of resolve(), it's not * clear what is counted. - * - * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException */ public function testCountFailsOutsideResolve() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\AccessException'); $this->resolver->setDefault('foo', 0); $this->resolver->setRequired('bar'); $this->resolver->setDefined('bar'); @@ -2007,12 +1898,10 @@ class OptionsResolverTest extends TestCase )); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value array is expected to be of type "float[][][][]", but one of the elements is of type "integer[][][][]". - */ public function testNestedArraysException() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value array is expected to be of type "float[][][][]", but one of the elements is of type "integer[][][][]".'); $this->resolver->setDefined('foo'); $this->resolver->setAllowedTypes('foo', 'float[][][][]'); @@ -2027,12 +1916,10 @@ class OptionsResolverTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value array is expected to be of type "int[][]", but one of the elements is of type "boolean[][]". - */ public function testNestedArrayException1() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value array is expected to be of type "int[][]", but one of the elements is of type "boolean[][]".'); $this->resolver->setDefined('foo'); $this->resolver->setAllowedTypes('foo', 'int[][]'); $this->resolver->resolve([ @@ -2042,12 +1929,10 @@ class OptionsResolverTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value array is expected to be of type "int[][]", but one of the elements is of type "boolean[][]". - */ public function testNestedArrayException2() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value array is expected to be of type "int[][]", but one of the elements is of type "boolean[][]".'); $this->resolver->setDefined('foo'); $this->resolver->setAllowedTypes('foo', 'int[][]'); $this->resolver->resolve([ @@ -2057,12 +1942,10 @@ class OptionsResolverTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value array is expected to be of type "string[][][]", but one of the elements is of type "string[][]". - */ public function testNestedArrayException3() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value array is expected to be of type "string[][][]", but one of the elements is of type "string[][]".'); $this->resolver->setDefined('foo'); $this->resolver->setAllowedTypes('foo', 'string[][][]'); $this->resolver->resolve([ @@ -2072,12 +1955,10 @@ class OptionsResolverTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value array is expected to be of type "string[][][]", but one of the elements is of type "integer[][][]". - */ public function testNestedArrayException4() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value array is expected to be of type "string[][][]", but one of the elements is of type "integer[][][]".'); $this->resolver->setDefined('foo'); $this->resolver->setAllowedTypes('foo', 'string[][][]'); $this->resolver->resolve([ @@ -2088,12 +1969,10 @@ class OptionsResolverTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "foo" with value array is expected to be of type "string[]", but one of the elements is of type "array[]". - */ public function testNestedArrayException5() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "foo" with value array is expected to be of type "string[]", but one of the elements is of type "array[]".'); $this->resolver->setDefined('foo'); $this->resolver->setAllowedTypes('foo', 'string[]'); $this->resolver->resolve([ @@ -2114,12 +1993,10 @@ class OptionsResolverTest extends TestCase $this->assertTrue($this->resolver->isNested('database')); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException - * @expectedExceptionMessage The option "foo" does not exist. Defined options are: "host", "port". - */ public function testFailsIfUndefinedNestedOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException'); + $this->expectExceptionMessage('The option "foo" does not exist. Defined options are: "host", "port".'); $this->resolver->setDefaults([ 'name' => 'default', 'database' => function (OptionsResolver $resolver) { @@ -2131,12 +2008,10 @@ class OptionsResolverTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\MissingOptionsException - * @expectedExceptionMessage The required option "host" is missing. - */ public function testFailsIfMissingRequiredNestedOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\MissingOptionsException'); + $this->expectExceptionMessage('The required option "host" is missing.'); $this->resolver->setDefaults([ 'name' => 'default', 'database' => function (OptionsResolver $resolver) { @@ -2148,12 +2023,10 @@ class OptionsResolverTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The option "logging" with value null is expected to be of type "bool", but is of type "NULL". - */ public function testFailsIfInvalidTypeNestedOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The option "logging" with value null is expected to be of type "bool", but is of type "NULL".'); $this->resolver->setDefaults([ 'name' => 'default', 'database' => function (OptionsResolver $resolver) { @@ -2167,12 +2040,10 @@ class OptionsResolverTest extends TestCase ]); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException - * @expectedExceptionMessage The nested option "database" with value null is expected to be of type array, but is of type "NULL". - */ public function testFailsIfNotArrayIsGivenForNestedOptions() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The nested option "database" with value null is expected to be of type array, but is of type "NULL".'); $this->resolver->setDefaults([ 'name' => 'default', 'database' => function (OptionsResolver $resolver) { @@ -2376,22 +2247,18 @@ class OptionsResolverTest extends TestCase $this->assertSame(['foo' => ['bar' => 'baz']], $this->resolver->resolve()); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException - */ public function testFailsIfCyclicDependencyBetweenSameNestedOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\OptionDefinitionException'); $this->resolver->setDefault('database', function (OptionsResolver $resolver, Options $parent) { $resolver->setDefault('replicas', $parent['database']); }); $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException - */ public function testFailsIfCyclicDependencyBetweenNestedOptionAndParentLazyOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\OptionDefinitionException'); $this->resolver->setDefaults([ 'version' => function (Options $options) { return $options['database']['server_version']; @@ -2403,11 +2270,9 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException - */ public function testFailsIfCyclicDependencyBetweenNormalizerAndNestedOption() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\OptionDefinitionException'); $this->resolver ->setDefault('name', 'default') ->setDefault('database', function (OptionsResolver $resolver, Options $parent) { @@ -2419,11 +2284,9 @@ class OptionsResolverTest extends TestCase $this->resolver->resolve(); } - /** - * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException - */ public function testFailsIfCyclicDependencyBetweenNestedOptions() { + $this->expectException('Symfony\Component\OptionsResolver\Exception\OptionDefinitionException'); $this->resolver->setDefault('database', function (OptionsResolver $resolver, Options $parent) { $resolver->setDefault('host', $parent['replica']['host']); }); diff --git a/src/Symfony/Component/Process/Tests/ProcessTest.php b/src/Symfony/Component/Process/Tests/ProcessTest.php index cdbb4d6922..47c5f096e3 100644 --- a/src/Symfony/Component/Process/Tests/ProcessTest.php +++ b/src/Symfony/Component/Process/Tests/ProcessTest.php @@ -50,13 +50,10 @@ class ProcessTest extends TestCase } } - /** - * @expectedException \Symfony\Component\Process\Exception\RuntimeException - * @expectedExceptionMessage The provided cwd " - * @expectedExceptionMessage "does not exist. - */ public function testInvalidCwd() { + $this->expectException('Symfony\Component\Process\Exception\RuntimeException'); + $this->expectExceptionMessageRegExp('/The provided cwd ".*" does not exist\./'); try { // Check that it works fine if the CWD exists $cmd = new Process(['echo', 'test'], __DIR__); @@ -82,19 +79,15 @@ class ProcessTest extends TestCase $this->assertEquals(E_USER_NOTICE, $actualError['type']); } - /** - * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException - */ public function testNegativeTimeoutFromConstructor() { + $this->expectException('Symfony\Component\Process\Exception\InvalidArgumentException'); $this->getProcess('', null, null, null, -1); } - /** - * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException - */ public function testNegativeTimeoutFromSetter() { + $this->expectException('Symfony\Component\Process\Exception\InvalidArgumentException'); $p = $this->getProcess(''); $p->setTimeout(-1); } @@ -280,12 +273,10 @@ class ProcessTest extends TestCase $this->assertSame('hello', $p->getOutput()); } - /** - * @expectedException \Symfony\Component\Process\Exception\LogicException - * @expectedExceptionMessage Input can not be set while the process is running. - */ public function testSetInputWhileRunningThrowsAnException() { + $this->expectException('Symfony\Component\Process\Exception\LogicException'); + $this->expectExceptionMessage('Input can not be set while the process is running.'); $process = $this->getProcessForCode('sleep(30);'); $process->start(); try { @@ -301,11 +292,11 @@ class ProcessTest extends TestCase /** * @dataProvider provideInvalidInputValues - * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException - * @expectedExceptionMessage Symfony\Component\Process\Process::setInput only accepts strings, Traversable objects or stream resources. */ public function testInvalidInput($value) { + $this->expectException('Symfony\Component\Process\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Symfony\Component\Process\Process::setInput only accepts strings, Traversable objects or stream resources.'); $process = $this->getProcess('foo'); $process->setInput($value); } @@ -510,12 +501,10 @@ class ProcessTest extends TestCase $this->assertTrue($process->isSuccessful()); } - /** - * @expectedException \Symfony\Component\Process\Exception\RuntimeException - * @expectedExceptionMessage TTY mode is not supported on Windows platform. - */ public function testTTYInWindowsEnvironment() { + $this->expectException('Symfony\Component\Process\Exception\RuntimeException'); + $this->expectExceptionMessage('TTY mode is not supported on Windows platform.'); if ('\\' !== \DIRECTORY_SEPARATOR) { $this->markTestSkipped('This test is for Windows platform only'); } @@ -559,11 +548,9 @@ class ProcessTest extends TestCase $this->assertEquals(0, $process->getExitCode()); } - /** - * @expectedException \Symfony\Component\Process\Exception\ProcessFailedException - */ public function testMustRunThrowsException() { + $this->expectException('Symfony\Component\Process\Exception\ProcessFailedException'); $process = $this->getProcess('exit 1'); $process->mustRun(); } @@ -713,12 +700,10 @@ class ProcessTest extends TestCase $this->assertEquals(15, $process->getTermSignal()); // SIGTERM } - /** - * @expectedException \Symfony\Component\Process\Exception\ProcessSignaledException - * @expectedExceptionMessage The process has been signaled with signal "9". - */ public function testProcessThrowsExceptionWhenExternallySignaled() { + $this->expectException('Symfony\Component\Process\Exception\ProcessSignaledException'); + $this->expectExceptionMessage('The process has been signaled with signal "9".'); if (!\function_exists('posix_kill')) { $this->markTestSkipped('Function posix_kill is required.'); } @@ -752,12 +737,10 @@ class ProcessTest extends TestCase $this->assertNotEquals($process1->getOutput(), $process2->getOutput()); } - /** - * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException - * @expectedExceptionMessage exceeded the timeout of 0.1 seconds. - */ public function testRunProcessWithTimeout() { + $this->expectException('Symfony\Component\Process\Exception\ProcessTimedOutException'); + $this->expectExceptionMessage('exceeded the timeout of 0.1 seconds.'); $process = $this->getProcessForCode('sleep(30);'); $process->setTimeout(0.1); $start = microtime(true); @@ -772,12 +755,10 @@ class ProcessTest extends TestCase throw $e; } - /** - * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException - * @expectedExceptionMessage exceeded the timeout of 0.1 seconds. - */ public function testIterateOverProcessWithTimeout() { + $this->expectException('Symfony\Component\Process\Exception\ProcessTimedOutException'); + $this->expectExceptionMessage('exceeded the timeout of 0.1 seconds.'); $process = $this->getProcessForCode('sleep(30);'); $process->setTimeout(0.1); $start = microtime(true); @@ -806,12 +787,10 @@ class ProcessTest extends TestCase $this->assertNull($process->checkTimeout()); } - /** - * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException - * @expectedExceptionMessage exceeded the timeout of 0.1 seconds. - */ public function testCheckTimeoutOnStartedProcess() { + $this->expectException('Symfony\Component\Process\Exception\ProcessTimedOutException'); + $this->expectExceptionMessage('exceeded the timeout of 0.1 seconds.'); $process = $this->getProcessForCode('sleep(33);'); $process->setTimeout(0.1); @@ -871,12 +850,10 @@ class ProcessTest extends TestCase } } - /** - * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException - * @expectedExceptionMessage exceeded the timeout of 0.1 seconds. - */ public function testStartAfterATimeout() { + $this->expectException('Symfony\Component\Process\Exception\ProcessTimedOutException'); + $this->expectExceptionMessage('exceeded the timeout of 0.1 seconds.'); $process = $this->getProcessForCode('sleep(35);'); $process->setTimeout(0.1); @@ -950,12 +927,10 @@ class ProcessTest extends TestCase $this->assertEquals(137, $process->getExitCode()); } - /** - * @expectedException \Symfony\Component\Process\Exception\LogicException - * @expectedExceptionMessage Can not send signal on a non running process. - */ public function testSignalProcessNotRunning() { + $this->expectException('Symfony\Component\Process\Exception\LogicException'); + $this->expectExceptionMessage('Can not send signal on a non running process.'); $process = $this->getProcess('foo'); $process->signal(1); // SIGHUP } @@ -986,11 +961,11 @@ class ProcessTest extends TestCase /** * @dataProvider provideMethodsThatNeedATerminatedProcess - * @expectedException \Symfony\Component\Process\Exception\LogicException - * @expectedExceptionMessage Process must be terminated before calling */ public function testMethodsThatNeedATerminatedProcess($method) { + $this->expectException('Symfony\Component\Process\Exception\LogicException'); + $this->expectExceptionMessage('Process must be terminated before calling'); $process = $this->getProcessForCode('sleep(37);'); $process->start(); try { @@ -1014,11 +989,9 @@ class ProcessTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\Process\Exception\RuntimeException - */ public function testWrongSignal() { + $this->expectException('Symfony\Component\Process\Exception\RuntimeException'); if ('\\' === \DIRECTORY_SEPARATOR) { $this->markTestSkipped('POSIX signals do not work on Windows'); } @@ -1045,23 +1018,19 @@ class ProcessTest extends TestCase $this->assertFalse($p->isOutputDisabled()); } - /** - * @expectedException \Symfony\Component\Process\Exception\RuntimeException - * @expectedExceptionMessage Disabling output while the process is running is not possible. - */ public function testDisableOutputWhileRunningThrowsException() { + $this->expectException('Symfony\Component\Process\Exception\RuntimeException'); + $this->expectExceptionMessage('Disabling output while the process is running is not possible.'); $p = $this->getProcessForCode('sleep(39);'); $p->start(); $p->disableOutput(); } - /** - * @expectedException \Symfony\Component\Process\Exception\RuntimeException - * @expectedExceptionMessage Enabling output while the process is running is not possible. - */ public function testEnableOutputWhileRunningThrowsException() { + $this->expectException('Symfony\Component\Process\Exception\RuntimeException'); + $this->expectExceptionMessage('Enabling output while the process is running is not possible.'); $p = $this->getProcessForCode('sleep(40);'); $p->disableOutput(); $p->start(); @@ -1078,23 +1047,19 @@ class ProcessTest extends TestCase $this->assertTrue($p->isOutputDisabled()); } - /** - * @expectedException \Symfony\Component\Process\Exception\LogicException - * @expectedExceptionMessage Output can not be disabled while an idle timeout is set. - */ public function testDisableOutputWhileIdleTimeoutIsSet() { + $this->expectException('Symfony\Component\Process\Exception\LogicException'); + $this->expectExceptionMessage('Output can not be disabled while an idle timeout is set.'); $process = $this->getProcess('foo'); $process->setIdleTimeout(1); $process->disableOutput(); } - /** - * @expectedException \Symfony\Component\Process\Exception\LogicException - * @expectedExceptionMessage timeout can not be set while the output is disabled. - */ public function testSetIdleTimeoutWhileOutputIsDisabled() { + $this->expectException('Symfony\Component\Process\Exception\LogicException'); + $this->expectExceptionMessage('timeout can not be set while the output is disabled.'); $process = $this->getProcess('foo'); $process->disableOutput(); $process->setIdleTimeout(1); @@ -1109,11 +1074,11 @@ class ProcessTest extends TestCase /** * @dataProvider provideOutputFetchingMethods - * @expectedException \Symfony\Component\Process\Exception\LogicException - * @expectedExceptionMessage Output has been disabled. */ public function testGetOutputWhileDisabled($fetchMethod) { + $this->expectException('Symfony\Component\Process\Exception\LogicException'); + $this->expectExceptionMessage('Output has been disabled.'); $p = $this->getProcessForCode('sleep(41);'); $p->disableOutput(); $p->start(); @@ -1521,22 +1486,18 @@ EOTXT; $this->assertSame('"DEF"', rtrim($p->getOutput())); } - /** - * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException - * @expectedExceptionMessage Command line is missing a value for key "$abc": echo "$abc". - */ public function testPreparedCommandWithMissingValue() { + $this->expectException('Symfony\Component\Process\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Command line is missing a value for key "$abc": echo "$abc".'); $p = Process::fromShellCommandline('echo "$abc"'); $p->run(null, ['bcd' => 'BCD']); } - /** - * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException - * @expectedExceptionMessage Command line is missing a value for key "$abc": echo "$abc". - */ public function testPreparedCommandWithNoValues() { + $this->expectException('Symfony\Component\Process\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Command line is missing a value for key "$abc": echo "$abc".'); $p = Process::fromShellCommandline('echo "$abc"'); $p->run(null, []); } diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorArrayAccessTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorArrayAccessTest.php index 5749cfae6f..071f70d360 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorArrayAccessTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorArrayAccessTest.php @@ -48,11 +48,9 @@ abstract class PropertyAccessorArrayAccessTest extends TestCase $this->assertSame($value, $this->propertyAccessor->getValue($collection, $path)); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchIndexException - */ public function testGetValueFailsIfNoSuchIndex() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchIndexException'); $this->propertyAccessor = PropertyAccess::createPropertyAccessorBuilder() ->enableExceptionOnInvalidIndex() ->getPropertyAccessor(); diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTest.php index 61ce5f1272..533de1173a 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTest.php @@ -11,6 +11,8 @@ namespace Symfony\Component\PropertyAccess\Tests; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; + class PropertyAccessorCollectionTest_Car { private $axes; @@ -100,6 +102,8 @@ class PropertyAccessorCollectionTest_CarStructure abstract class PropertyAccessorCollectionTest extends PropertyAccessorArrayAccessTest { + use ForwardCompatTestTrait; + public function testSetValueCallsAdderAndRemoverForCollections() { $axesBefore = $this->getContainer([1 => 'second', 3 => 'fourth', 4 => 'fifth']); @@ -146,12 +150,10 @@ abstract class PropertyAccessorCollectionTest extends PropertyAccessorArrayAcces $this->propertyAccessor->setValue($car, 'structure.axes', $axesAfter); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException - * @expectedExceptionMessageRegExp /Could not determine access type for property "axes" in class "Mock_PropertyAccessorCollectionTest_CarNoAdderAndRemover_[^"]*"./ - */ public function testSetValueFailsIfNoAdderNorRemoverFound() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException'); + $this->expectExceptionMessageRegExp('/Could not determine access type for property "axes" in class "Mock_PropertyAccessorCollectionTest_CarNoAdderAndRemover_[^"]*"./'); $car = $this->getMockBuilder(__CLASS__.'_CarNoAdderAndRemover')->getMock(); $axesBefore = $this->getContainer([1 => 'second', 3 => 'fourth']); $axesAfter = $this->getContainer([0 => 'first', 1 => 'second', 2 => 'third']); @@ -187,12 +189,10 @@ abstract class PropertyAccessorCollectionTest extends PropertyAccessorArrayAcces $this->assertFalse($this->propertyAccessor->isWritable($car, 'axes')); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException - * @expectedExceptionMessageRegExp /Could not determine access type for property "axes" in class "Symfony\\Component\\PropertyAccess\\Tests\\PropertyAccessorCollectionTest_Car[^"]*": The property "axes" in class "Symfony\\Component\\PropertyAccess\\Tests\\PropertyAccessorCollectionTest_Car[^"]*" can be defined with the methods "addAxis\(\)", "removeAxis\(\)" but the new value must be an array or an instance of \\Traversable, "string" given./ - */ public function testSetValueFailsIfAdderAndRemoverExistButValueIsNotTraversable() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException'); + $this->expectExceptionMessageRegExp('/Could not determine access type for property "axes" in class "Symfony\\\\Component\\\\PropertyAccess\\\\Tests\\\\PropertyAccessorCollectionTest_Car[^"]*": The property "axes" in class "Symfony\\\\Component\\\\PropertyAccess\\\\Tests\\\\PropertyAccessorCollectionTest_Car[^"]*" can be defined with the methods "addAxis\(\)", "removeAxis\(\)" but the new value must be an array or an instance of \\\\Traversable, "string" given./'); $car = new PropertyAccessorCollectionTest_Car(); $this->propertyAccessor->setValue($car, 'axes', 'Not an array or Traversable'); diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php index d9eef22357..c2bc79219d 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php @@ -99,10 +99,10 @@ class PropertyAccessorTest extends TestCase /** * @dataProvider getPathsWithMissingProperty - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException */ public function testGetValueThrowsExceptionIfPropertyNotFound($objectOrArray, $path) { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException'); $this->propertyAccessor->getValue($objectOrArray, $path); } @@ -126,19 +126,17 @@ class PropertyAccessorTest extends TestCase /** * @dataProvider getPathsWithMissingIndex - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchIndexException */ public function testGetValueThrowsExceptionIfIndexNotFoundAndIndexExceptionsEnabled($objectOrArray, $path) { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchIndexException'); $this->propertyAccessor = new PropertyAccessor(false, true); $this->propertyAccessor->getValue($objectOrArray, $path); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchIndexException - */ public function testGetValueThrowsExceptionIfNotArrayAccess() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchIndexException'); $this->propertyAccessor->getValue(new \stdClass(), '[index]'); } @@ -185,11 +183,9 @@ class PropertyAccessorTest extends TestCase $this->assertSame(['Bernhard'], $object->firstName); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException - */ public function testGetValueDoesNotReadMagicCallByDefault() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException'); $this->propertyAccessor->getValue(new TestClassMagicCall('Bernhard'), 'magicCallProperty'); } @@ -210,11 +206,11 @@ class PropertyAccessorTest extends TestCase /** * @dataProvider getPathsWithUnexpectedType - * @expectedException \Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException - * @expectedExceptionMessage PropertyAccessor requires a graph of objects or arrays to operate on */ public function testGetValueThrowsExceptionIfNotObjectOrArray($objectOrArray, $path) { + $this->expectException('Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException'); + $this->expectExceptionMessage('PropertyAccessor requires a graph of objects or arrays to operate on'); $this->propertyAccessor->getValue($objectOrArray, $path); } @@ -230,10 +226,10 @@ class PropertyAccessorTest extends TestCase /** * @dataProvider getPathsWithMissingProperty - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException */ public function testSetValueThrowsExceptionIfPropertyNotFound($objectOrArray, $path) { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException'); $this->propertyAccessor->setValue($objectOrArray, $path, 'Updated'); } @@ -258,11 +254,9 @@ class PropertyAccessorTest extends TestCase $this->assertSame('Updated', $this->propertyAccessor->getValue($objectOrArray, $path)); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchIndexException - */ public function testSetValueThrowsExceptionIfNotArrayAccess() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchIndexException'); $object = new \stdClass(); $this->propertyAccessor->setValue($object, '[index]', 'Updated'); @@ -277,21 +271,17 @@ class PropertyAccessorTest extends TestCase $this->assertEquals('Updated', $author->__get('magicProperty')); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException - */ public function testSetValueThrowsExceptionIfThereAreMissingParameters() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException'); $object = new TestClass('Bernhard'); $this->propertyAccessor->setValue($object, 'publicAccessorWithMoreRequiredParameters', 'Updated'); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException - */ public function testSetValueDoesNotUpdateMagicCallByDefault() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException'); $author = new TestClassMagicCall('Bernhard'); $this->propertyAccessor->setValue($author, 'magicCallProperty', 'Updated'); @@ -310,11 +300,11 @@ class PropertyAccessorTest extends TestCase /** * @dataProvider getPathsWithUnexpectedType - * @expectedException \Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException - * @expectedExceptionMessage PropertyAccessor requires a graph of objects or arrays to operate on */ public function testSetValueThrowsExceptionIfNotObjectOrArray($objectOrArray, $path) { + $this->expectException('Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException'); + $this->expectExceptionMessage('PropertyAccessor requires a graph of objects or arrays to operate on'); $this->propertyAccessor->setValue($objectOrArray, $path, 'value'); } @@ -547,23 +537,19 @@ class PropertyAccessorTest extends TestCase $this->assertEquals($value, $this->propertyAccessor->isWritable($object, $path)); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\InvalidArgumentException - * @expectedExceptionMessage Expected argument of type "DateTime", "string" given at property path "date" - */ public function testThrowTypeError() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Expected argument of type "DateTime", "string" given at property path "date"'); $object = new TypeHinted(); $this->propertyAccessor->setValue($object, 'date', 'This is a string, \DateTime expected.'); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\InvalidArgumentException - * @expectedExceptionMessage Expected argument of type "DateTime", "NULL" given - */ public function testThrowTypeErrorWithNullArgument() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Expected argument of type "DateTime", "NULL" given'); $object = new TypeHinted(); $this->propertyAccessor->setValue($object, 'date', null); @@ -612,12 +598,10 @@ class PropertyAccessorTest extends TestCase $this->assertSame('2', $propertyAccessor->getValue($obj, 'a%2Fb')); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\InvalidArgumentException - * @expectedExceptionMessage Expected argument of type "Countable", "string" given - */ public function testThrowTypeErrorWithInterface() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Expected argument of type "Countable", "string" given'); $object = new TypeHinted(); $this->propertyAccessor->setValue($object, 'countable', 'This is a string, \Countable expected.'); @@ -634,11 +618,9 @@ class PropertyAccessorTest extends TestCase $this->assertEquals($value, $propertyAccessor->getValue($obj, 'foo')); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException - */ public function testAnonymousClassReadThrowExceptionOnInvalidPropertyPath() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException'); $obj = $this->generateAnonymousClass('bar'); $this->propertyAccessor->getValue($obj, 'invalid_property'); @@ -696,31 +678,25 @@ class PropertyAccessorTest extends TestCase return $obj; } - /** - * @expectedException \TypeError - */ public function testThrowTypeErrorInsideSetterCall() { + $this->expectException('TypeError'); $object = new TestClassTypeErrorInsideCall(); $this->propertyAccessor->setValue($object, 'property', 'foo'); } - /** - * @expectedException \TypeError - */ public function testDoNotDiscardReturnTypeError() { + $this->expectException('TypeError'); $object = new ReturnTyped(); $this->propertyAccessor->setValue($object, 'foos', [new \DateTime()]); } - /** - * @expectedException \TypeError - */ public function testDoNotDiscardReturnTypeErrorWhenWriterMethodIsMisconfigured() { + $this->expectException('TypeError'); $object = new ReturnTyped(); $this->propertyAccessor->setValue($object, 'name', 'foo'); @@ -768,52 +744,42 @@ class PropertyAccessorTest extends TestCase $this->assertEquals(['aeroplane'], $object->getAircraft()); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException - * @expectedExceptionMessageRegExp /.*The add method "addFoo" in class "Symfony\\Component\\PropertyAccess\\Tests\\Fixtures\\TestAdderRemoverInvalidMethods" was found, but the corresponding remove method "removeFoo" was not found\./ - */ public function testAdderWithoutRemover() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException'); + $this->expectExceptionMessageRegExp('/.*The add method "addFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidMethods" was found, but the corresponding remove method "removeFoo" was not found\./'); $object = new TestAdderRemoverInvalidMethods(); $this->propertyAccessor->setValue($object, 'foos', [1, 2]); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException - * @expectedExceptionMessageRegExp /.*The remove method "removeBar" in class "Symfony\\Component\\PropertyAccess\\Tests\\Fixtures\\TestAdderRemoverInvalidMethods" was found, but the corresponding add method "addBar" was not found\./ - */ public function testRemoverWithoutAdder() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException'); + $this->expectExceptionMessageRegExp('/.*The remove method "removeBar" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidMethods" was found, but the corresponding add method "addBar" was not found\./'); $object = new TestAdderRemoverInvalidMethods(); $this->propertyAccessor->setValue($object, 'bars', [1, 2]); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException - * @expectedExceptionMessageRegExp /.*The method "addFoo" in class "Symfony\\Component\\PropertyAccess\\Tests\\Fixtures\\TestAdderRemoverInvalidArgumentLength" requires 0 arguments, but should accept only 1\. The method "removeFoo" in class "Symfony\\Component\\PropertyAccess\\Tests\\Fixtures\\TestAdderRemoverInvalidArgumentLength" requires 2 arguments, but should accept only 1\./ - */ public function testAdderAndRemoveNeedsTheExactParametersDefined() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException'); + $this->expectExceptionMessageRegExp('/.*The method "addFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidArgumentLength" requires 0 arguments, but should accept only 1\. The method "removeFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidArgumentLength" requires 2 arguments, but should accept only 1\./'); $object = new TestAdderRemoverInvalidArgumentLength(); $this->propertyAccessor->setValue($object, 'foo', [1, 2]); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException - * @expectedExceptionMessageRegExp /.*The method "setBar" in class "Symfony\\Component\\PropertyAccess\\Tests\\Fixtures\\TestAdderRemoverInvalidArgumentLength" requires 2 arguments, but should accept only 1\./ - */ public function testSetterNeedsTheExactParametersDefined() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException'); + $this->expectExceptionMessageRegExp('/.*The method "setBar" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidArgumentLength" requires 2 arguments, but should accept only 1\./'); $object = new TestAdderRemoverInvalidArgumentLength(); $this->propertyAccessor->setValue($object, 'bar', [1, 2]); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException - * @expectedExceptionMessageRegExp /.*The method "setFoo" in class "Symfony\\Component\\PropertyAccess\\Tests\\Fixtures\\TestClassSetValue" was found but does not have public access./ - */ public function testSetterNeedsPublicAccess() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException'); + $this->expectExceptionMessageRegExp('/.*The method "setFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestClassSetValue" was found but does not have public access./'); $object = new TestClassSetValue(0); $this->propertyAccessor->setValue($object, 'foo', 1); } diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyPathBuilderTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyPathBuilderTest.php index fcc400b8c5..e4ff364439 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyPathBuilderTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyPathBuilderTest.php @@ -119,19 +119,15 @@ class PropertyPathBuilderTest extends TestCase $this->assertEquals($path, $this->builder->getPropertyPath()); } - /** - * @expectedException \OutOfBoundsException - */ public function testReplaceByIndexDoesNotAllowInvalidOffsets() { + $this->expectException('OutOfBoundsException'); $this->builder->replaceByIndex(6, 'new1'); } - /** - * @expectedException \OutOfBoundsException - */ public function testReplaceByIndexDoesNotAllowNegativeOffsets() { + $this->expectException('OutOfBoundsException'); $this->builder->replaceByIndex(-1, 'new1'); } @@ -153,19 +149,15 @@ class PropertyPathBuilderTest extends TestCase $this->assertEquals($path, $this->builder->getPropertyPath()); } - /** - * @expectedException \OutOfBoundsException - */ public function testReplaceByPropertyDoesNotAllowInvalidOffsets() { + $this->expectException('OutOfBoundsException'); $this->builder->replaceByProperty(6, 'new1'); } - /** - * @expectedException \OutOfBoundsException - */ public function testReplaceByPropertyDoesNotAllowNegativeOffsets() { + $this->expectException('OutOfBoundsException'); $this->builder->replaceByProperty(-1, 'new1'); } @@ -198,10 +190,10 @@ class PropertyPathBuilderTest extends TestCase /** * @dataProvider provideInvalidOffsets - * @expectedException \OutOfBoundsException */ public function testReplaceDoesNotAllowInvalidOffsets($offset) { + $this->expectException('OutOfBoundsException'); $this->builder->replace($offset, 1, new PropertyPath('new1[new2].new3')); } @@ -273,19 +265,15 @@ class PropertyPathBuilderTest extends TestCase $this->assertEquals($path, $this->builder->getPropertyPath()); } - /** - * @expectedException \OutOfBoundsException - */ public function testRemoveDoesNotAllowInvalidOffsets() { + $this->expectException('OutOfBoundsException'); $this->builder->remove(6); } - /** - * @expectedException \OutOfBoundsException - */ public function testRemoveDoesNotAllowNegativeOffsets() { + $this->expectException('OutOfBoundsException'); $this->builder->remove(-1); } diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyPathTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyPathTest.php index c58ebf510c..dbe63a258f 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyPathTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyPathTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\PropertyAccess\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\PropertyAccess\PropertyPath; class PropertyPathTest extends TestCase { + use ForwardCompatTestTrait; + public function testToString() { $path = new PropertyPath('reference.traversable[index].property'); @@ -23,19 +26,15 @@ class PropertyPathTest extends TestCase $this->assertEquals('reference.traversable[index].property', $path->__toString()); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException - */ public function testDotIsRequiredBeforeProperty() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException'); new PropertyPath('[index]property'); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException - */ public function testDotCannotBePresentAtTheBeginning() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException'); new PropertyPath('.property'); } @@ -54,34 +53,28 @@ class PropertyPathTest extends TestCase /** * @dataProvider providePathsContainingUnexpectedCharacters - * @expectedException \Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException */ public function testUnexpectedCharacters($path) { + $this->expectException('Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException'); new PropertyPath($path); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException - */ public function testPathCannotBeEmpty() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException'); new PropertyPath(''); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\InvalidArgumentException - */ public function testPathCannotBeNull() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\InvalidArgumentException'); new PropertyPath(null); } - /** - * @expectedException \Symfony\Component\PropertyAccess\Exception\InvalidArgumentException - */ public function testPathCannotBeFalse() { + $this->expectException('Symfony\Component\PropertyAccess\Exception\InvalidArgumentException'); new PropertyPath(false); } @@ -128,21 +121,17 @@ class PropertyPathTest extends TestCase $this->assertEquals('child', $propertyPath->getElement(2)); } - /** - * @expectedException \OutOfBoundsException - */ public function testGetElementDoesNotAcceptInvalidIndices() { + $this->expectException('OutOfBoundsException'); $propertyPath = new PropertyPath('grandpa.parent[child]'); $propertyPath->getElement(3); } - /** - * @expectedException \OutOfBoundsException - */ public function testGetElementDoesNotAcceptNegativeIndices() { + $this->expectException('OutOfBoundsException'); $propertyPath = new PropertyPath('grandpa.parent[child]'); $propertyPath->getElement(-1); @@ -156,21 +145,17 @@ class PropertyPathTest extends TestCase $this->assertFalse($propertyPath->isProperty(2)); } - /** - * @expectedException \OutOfBoundsException - */ public function testIsPropertyDoesNotAcceptInvalidIndices() { + $this->expectException('OutOfBoundsException'); $propertyPath = new PropertyPath('grandpa.parent[child]'); $propertyPath->isProperty(3); } - /** - * @expectedException \OutOfBoundsException - */ public function testIsPropertyDoesNotAcceptNegativeIndices() { + $this->expectException('OutOfBoundsException'); $propertyPath = new PropertyPath('grandpa.parent[child]'); $propertyPath->isProperty(-1); @@ -184,21 +169,17 @@ class PropertyPathTest extends TestCase $this->assertTrue($propertyPath->isIndex(2)); } - /** - * @expectedException \OutOfBoundsException - */ public function testIsIndexDoesNotAcceptInvalidIndices() { + $this->expectException('OutOfBoundsException'); $propertyPath = new PropertyPath('grandpa.parent[child]'); $propertyPath->isIndex(3); } - /** - * @expectedException \OutOfBoundsException - */ public function testIsIndexDoesNotAcceptNegativeIndices() { + $this->expectException('OutOfBoundsException'); $propertyPath = new PropertyPath('grandpa.parent[child]'); $propertyPath->isIndex(-1); diff --git a/src/Symfony/Component/PropertyInfo/Tests/TypeTest.php b/src/Symfony/Component/PropertyInfo/Tests/TypeTest.php index cd1cab9167..ced7231450 100644 --- a/src/Symfony/Component/PropertyInfo/Tests/TypeTest.php +++ b/src/Symfony/Component/PropertyInfo/Tests/TypeTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\PropertyInfo\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\PropertyInfo\Type; /** @@ -19,6 +20,8 @@ use Symfony\Component\PropertyInfo\Type; */ class TypeTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstruct() { $type = new Type('object', true, 'ArrayObject', true, new Type('int'), new Type('string')); @@ -43,12 +46,10 @@ class TypeTest extends TestCase $this->assertSame('iterable', $type->getBuiltinType()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage "foo" is not a valid PHP type. - */ public function testInvalidType() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('"foo" is not a valid PHP type.'); new Type('foo'); } } diff --git a/src/Symfony/Component/Routing/Tests/Annotation/RouteTest.php b/src/Symfony/Component/Routing/Tests/Annotation/RouteTest.php index 9697aac88b..2f066f7cad 100644 --- a/src/Symfony/Component/Routing/Tests/Annotation/RouteTest.php +++ b/src/Symfony/Component/Routing/Tests/Annotation/RouteTest.php @@ -12,23 +12,22 @@ namespace Symfony\Component\Routing\Tests\Annotation; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Routing\Annotation\Route; class RouteTest extends TestCase { - /** - * @expectedException \BadMethodCallException - */ + use ForwardCompatTestTrait; + public function testInvalidRouteParameter() { + $this->expectException('BadMethodCallException'); $route = new Route(['foo' => 'bar']); } - /** - * @expectedException \BadMethodCallException - */ public function testTryingToSetLocalesDirectly() { + $this->expectException('BadMethodCallException'); $route = new Route(['locales' => ['nl' => 'bar']]); } diff --git a/src/Symfony/Component/Routing/Tests/Generator/Dumper/CompiledUrlGeneratorDumperTest.php b/src/Symfony/Component/Routing/Tests/Generator/Dumper/CompiledUrlGeneratorDumperTest.php index e6b076302c..513e1c80e1 100644 --- a/src/Symfony/Component/Routing/Tests/Generator/Dumper/CompiledUrlGeneratorDumperTest.php +++ b/src/Symfony/Component/Routing/Tests/Generator/Dumper/CompiledUrlGeneratorDumperTest.php @@ -116,12 +116,10 @@ class CompiledUrlGeneratorDumperTest extends TestCase $this->assertEquals('/app.php/foo', $projectUrlGenerator->generate('test')); } - /** - * @expectedException \Symfony\Component\Routing\Exception\RouteNotFoundException - * @expectedExceptionMessage Unable to generate a URL for the named route "test" as such route does not exist. - */ public function testDumpWithRouteNotFoundLocalizedRoutes() { + $this->expectException('Symfony\Component\Routing\Exception\RouteNotFoundException'); + $this->expectExceptionMessage('Unable to generate a URL for the named route "test" as such route does not exist.'); $this->routeCollection->add('test.en', (new Route('/testing/is/fun'))->setDefault('_locale', 'en')->setDefault('_canonical_route', 'test')); $code = $this->generatorDumper->dump(); @@ -178,11 +176,9 @@ class CompiledUrlGeneratorDumperTest extends TestCase $this->assertEquals('/app.php/testing2', $relativeUrlWithoutParameter); } - /** - * @expectedException \InvalidArgumentException - */ public function testDumpWithoutRoutes() { + $this->expectException('InvalidArgumentException'); file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump()); $projectUrlGenerator = new CompiledUrlGenerator(require $this->testTmpFilepath, new RequestContext('/app.php')); @@ -190,11 +186,9 @@ class CompiledUrlGeneratorDumperTest extends TestCase $projectUrlGenerator->generate('Test', []); } - /** - * @expectedException \Symfony\Component\Routing\Exception\RouteNotFoundException - */ public function testGenerateNonExistingRoute() { + $this->expectException('Symfony\Component\Routing\Exception\RouteNotFoundException'); $this->routeCollection->add('Test', new Route('/test')); file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump()); diff --git a/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php b/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php index 77a2098ab9..c9e3753d35 100644 --- a/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php +++ b/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php @@ -79,11 +79,9 @@ class UrlGeneratorTest extends TestCase $this->assertEquals('/app.php/testing', $url); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testRelativeUrlWithNullParameterButNotOptional() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/testing/{foo}/bar', ['foo' => null])); // This must raise an exception because the default requirement for "foo" is "[^/]+" which is not met with these params. // Generating path "/testing//bar" would be wrong as matching this route would fail. @@ -241,20 +239,16 @@ class UrlGeneratorTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\Routing\Exception\RouteNotFoundException - */ public function testGenerateWithoutRoutes() { + $this->expectException('Symfony\Component\Routing\Exception\RouteNotFoundException'); $routes = $this->getRoutes('foo', new Route('/testing/{foo}')); $this->getGenerator($routes)->generate('test', [], UrlGeneratorInterface::ABSOLUTE_URL); } - /** - * @expectedException \Symfony\Component\Routing\Exception\RouteNotFoundException - */ public function testGenerateWithInvalidLocale() { + $this->expectException('Symfony\Component\Routing\Exception\RouteNotFoundException'); $routes = new RouteCollection(); $route = new Route(''); @@ -273,29 +267,23 @@ class UrlGeneratorTest extends TestCase $generator->generate($name); } - /** - * @expectedException \Symfony\Component\Routing\Exception\MissingMandatoryParametersException - */ public function testGenerateForRouteWithoutMandatoryParameter() { + $this->expectException('Symfony\Component\Routing\Exception\MissingMandatoryParametersException'); $routes = $this->getRoutes('test', new Route('/testing/{foo}')); $this->getGenerator($routes)->generate('test', [], UrlGeneratorInterface::ABSOLUTE_URL); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testGenerateForRouteWithInvalidOptionalParameter() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/testing/{foo}', ['foo' => '1'], ['foo' => 'd+'])); $this->getGenerator($routes)->generate('test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_URL); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testGenerateForRouteWithInvalidParameter() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/testing/{foo}', [], ['foo' => '1|2'])); $this->getGenerator($routes)->generate('test', ['foo' => '0'], UrlGeneratorInterface::ABSOLUTE_URL); } @@ -327,29 +315,23 @@ class UrlGeneratorTest extends TestCase $this->assertSame('/app.php/testing/bar', $generator->generate('test', ['foo' => 'bar'])); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testGenerateForRouteWithInvalidMandatoryParameter() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/testing/{foo}', [], ['foo' => 'd+'])); $this->getGenerator($routes)->generate('test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_URL); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testGenerateForRouteWithInvalidUtf8Parameter() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/testing/{foo}', [], ['foo' => '\pL+'], ['utf8' => true])); $this->getGenerator($routes)->generate('test', ['foo' => 'abc123'], UrlGeneratorInterface::ABSOLUTE_URL); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testRequiredParamAndEmptyPassed() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/{slug}', [], ['slug' => '.+'])); $this->getGenerator($routes)->generate('test', ['slug' => '']); } @@ -509,31 +491,25 @@ class UrlGeneratorTest extends TestCase $this->assertSame('/app.php/index.mobile.html', $generator->generate('test', ['page' => 'index'])); } - /** - * @expectedException \Symfony\Component\Routing\Exception\MissingMandatoryParametersException - */ public function testImportantVariableWithNoDefault() { + $this->expectException('Symfony\Component\Routing\Exception\MissingMandatoryParametersException'); $routes = $this->getRoutes('test', new Route('/{page}.{!_format}')); $generator = $this->getGenerator($routes); $generator->generate('test', ['page' => 'index']); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testDefaultRequirementOfVariableDisallowsSlash() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/{page}.{_format}')); $this->getGenerator($routes)->generate('test', ['page' => 'index', '_format' => 'sl/ash']); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testDefaultRequirementOfVariableDisallowsNextSeparator() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/{page}.{_format}')); $this->getGenerator($routes)->generate('test', ['page' => 'do.t', '_format' => 'html']); } @@ -559,29 +535,23 @@ class UrlGeneratorTest extends TestCase $this->assertEquals('http://fr.example.com/app.php/Fabien', $this->getGenerator($routes, ['host' => 'fr.example.com'])->generate('test', ['name' => 'Fabien', 'locale' => 'fr'], UrlGeneratorInterface::ABSOLUTE_URL)); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testUrlWithInvalidParameterInHost() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/', [], ['foo' => 'bar'], [], '{foo}.example.com')); $this->getGenerator($routes)->generate('test', ['foo' => 'baz'], UrlGeneratorInterface::ABSOLUTE_PATH); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testUrlWithInvalidParameterInHostWhenParamHasADefaultValue() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/', ['foo' => 'bar'], ['foo' => 'bar'], [], '{foo}.example.com')); $this->getGenerator($routes)->generate('test', ['foo' => 'baz'], UrlGeneratorInterface::ABSOLUTE_PATH); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testUrlWithInvalidParameterEqualsDefaultValueInHost() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/', ['foo' => 'baz'], ['foo' => 'bar'], [], '{foo}.example.com')); $this->getGenerator($routes)->generate('test', ['foo' => 'baz'], UrlGeneratorInterface::ABSOLUTE_PATH); } diff --git a/src/Symfony/Component/Routing/Tests/Loader/AnnotationClassLoaderTest.php b/src/Symfony/Component/Routing/Tests/Loader/AnnotationClassLoaderTest.php index e86cb26cc7..0d2c99fea5 100644 --- a/src/Symfony/Component/Routing/Tests/Loader/AnnotationClassLoaderTest.php +++ b/src/Symfony/Component/Routing/Tests/Loader/AnnotationClassLoaderTest.php @@ -93,12 +93,11 @@ class AnnotationClassLoaderTest extends AbstractAnnotationLoaderTest $this->assertEquals('/path', $routes->get('action')->getPath()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage A placeholder name must be a string (0 given). Did you forget to specify the placeholder key for the requirement "foo" - */ public function testRequirementsWithoutPlaceholderName() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('A placeholder name must be a string (0 given). Did you forget to specify the placeholder key for the requirement "foo"'); + $this->loader->load(RequirementsWithoutPlaceholderNameController::class); } diff --git a/src/Symfony/Component/Routing/Tests/Loader/AnnotationFileLoaderTest.php b/src/Symfony/Component/Routing/Tests/Loader/AnnotationFileLoaderTest.php index 3981b9377e..3ef7b7c157 100644 --- a/src/Symfony/Component/Routing/Tests/Loader/AnnotationFileLoaderTest.php +++ b/src/Symfony/Component/Routing/Tests/Loader/AnnotationFileLoaderTest.php @@ -45,12 +45,10 @@ class AnnotationFileLoaderTest extends AbstractAnnotationLoaderTest $this->loader->load(__DIR__.'/../Fixtures/AnnotatedClasses/FooTrait.php'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Did you forgot to add the "expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Did you forgot to add the "loader->load(__DIR__.'/../Fixtures/OtherAnnotatedClasses/NoStartTagClass.php'); } diff --git a/src/Symfony/Component/Routing/Tests/Loader/ObjectLoaderTest.php b/src/Symfony/Component/Routing/Tests/Loader/ObjectLoaderTest.php index 1267f540d0..bf94ef34ae 100644 --- a/src/Symfony/Component/Routing/Tests/Loader/ObjectLoaderTest.php +++ b/src/Symfony/Component/Routing/Tests/Loader/ObjectLoaderTest.php @@ -41,11 +41,11 @@ class ObjectLoaderTest extends TestCase } /** - * @expectedException \InvalidArgumentException * @dataProvider getBadResourceStrings */ public function testExceptionWithoutSyntax(string $resourceString): void { + $this->expectException('InvalidArgumentException'); $loader = new TestObjectLoader(); $loader->load($resourceString); } @@ -62,31 +62,25 @@ class ObjectLoaderTest extends TestCase ]; } - /** - * @expectedException \LogicException - */ public function testExceptionOnNoObjectReturned() { + $this->expectException('LogicException'); $loader = new TestObjectLoader(); $loader->loaderMap = ['my_service' => 'NOT_AN_OBJECT']; $loader->load('my_service::method'); } - /** - * @expectedException \BadMethodCallException - */ public function testExceptionOnBadMethod() { + $this->expectException('BadMethodCallException'); $loader = new TestObjectLoader(); $loader->loaderMap = ['my_service' => new \stdClass()]; $loader->load('my_service::method'); } - /** - * @expectedException \LogicException - */ public function testExceptionOnMethodNotReturningCollection() { + $this->expectException('LogicException'); $service = $this->getMockBuilder('stdClass') ->setMethods(['loadRoutes']) ->getMock(); diff --git a/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php b/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php index da86e6308c..ff2f2f8add 100644 --- a/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php +++ b/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Routing\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Routing\Loader\XmlFileLoader; @@ -21,6 +22,8 @@ use Symfony\Component\Routing\Tests\Fixtures\CustomXmlFileLoader; class XmlFileLoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testSupports() { $loader = new XmlFileLoader($this->getMockBuilder('Symfony\Component\Config\FileLocator')->getMock()); @@ -201,21 +204,21 @@ class XmlFileLoaderTest extends TestCase } /** - * @expectedException \InvalidArgumentException * @dataProvider getPathsToInvalidFiles */ public function testLoadThrowsExceptionWithInvalidFile($filePath) { + $this->expectException('InvalidArgumentException'); $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); $loader->load($filePath); } /** - * @expectedException \InvalidArgumentException * @dataProvider getPathsToInvalidFiles */ public function testLoadThrowsExceptionWithInvalidFileEvenWithoutSchemaValidation($filePath) { + $this->expectException('InvalidArgumentException'); $loader = new CustomXmlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); $loader->load($filePath); } @@ -225,12 +228,10 @@ class XmlFileLoaderTest extends TestCase return [['nonvalidnode.xml'], ['nonvalidroute.xml'], ['nonvalid.xml'], ['missing_id.xml'], ['missing_path.xml']]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Document types are not allowed. - */ public function testDocTypeIsNotAllowed() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Document types are not allowed.'); $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); $loader->load('withdoctype.xml'); } @@ -435,12 +436,10 @@ class XmlFileLoaderTest extends TestCase $this->assertSame('AppBundle:Blog:list', $route->getDefault('_controller')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /The routing file "[^"]*" must not specify both the "controller" attribute and the defaults key "_controller" for "app_blog"/ - */ public function testOverrideControllerInDefaults() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The routing file "[^"]*" must not specify both the "controller" attribute and the defaults key "_controller" for "app_blog"/'); $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); $loader->load('override_defaults.xml'); } @@ -469,12 +468,10 @@ class XmlFileLoaderTest extends TestCase yield ['import__controller.xml']; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /The routing file "[^"]*" must not specify both the "controller" attribute and the defaults key "_controller" for the "import" tag/ - */ public function testImportWithOverriddenController() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The routing file "[^"]*" must not specify both the "controller" attribute and the defaults key "_controller" for the "import" tag/'); $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); $loader->load('import_override_defaults.xml'); } diff --git a/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php index ce908f828c..7aa48fc74f 100644 --- a/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Routing\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Routing\Loader\YamlFileLoader; @@ -20,6 +21,8 @@ use Symfony\Component\Routing\RouteCollection; class YamlFileLoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testSupports() { $loader = new YamlFileLoader($this->getMockBuilder('Symfony\Component\Config\FileLocator')->getMock()); @@ -43,11 +46,11 @@ class YamlFileLoaderTest extends TestCase } /** - * @expectedException \InvalidArgumentException * @dataProvider getPathsToInvalidFiles */ public function testLoadThrowsExceptionWithInvalidFile($filePath) { + $this->expectException('InvalidArgumentException'); $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); $loader->load($filePath); } @@ -141,12 +144,10 @@ class YamlFileLoaderTest extends TestCase $this->assertSame('AppBundle:Blog:list', $route->getDefault('_controller')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /The routing file "[^"]*" must not specify both the "controller" key and the defaults key "_controller" for "app_blog"/ - */ public function testOverrideControllerInDefaults() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The routing file "[^"]*" must not specify both the "controller" key and the defaults key "_controller" for "app_blog"/'); $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); $loader->load('override_defaults.yml'); } @@ -175,12 +176,10 @@ class YamlFileLoaderTest extends TestCase yield ['import__controller.yml']; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /The routing file "[^"]*" must not specify both the "controller" key and the defaults key "_controller" for "_static"/ - */ public function testImportWithOverriddenController() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The routing file "[^"]*" must not specify both the "controller" key and the defaults key "_controller" for "_static"/'); $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); $loader->load('import_override_defaults.yml'); } @@ -381,12 +380,11 @@ class YamlFileLoaderTest extends TestCase $this->assertEquals('/no-slash', $routeCollection->get('b_app_homepage')->getPath()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage A placeholder name must be a string (0 given). Did you forget to specify the placeholder key for the requirement "\d+" of route "foo" - */ public function testRequirementsWithoutPlaceholderName() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('A placeholder name must be a string (0 given). Did you forget to specify the placeholder key for the requirement "\\d+" of route "foo"'); + $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); $loader->load('requirements_without_placeholder_name.yml'); } diff --git a/src/Symfony/Component/Routing/Tests/Matcher/Dumper/CompiledUrlMatcherDumperTest.php b/src/Symfony/Component/Routing/Tests/Matcher/Dumper/CompiledUrlMatcherDumperTest.php index e0e7018cc3..c90c448f95 100644 --- a/src/Symfony/Component/Routing/Tests/Matcher/Dumper/CompiledUrlMatcherDumperTest.php +++ b/src/Symfony/Component/Routing/Tests/Matcher/Dumper/CompiledUrlMatcherDumperTest.php @@ -474,12 +474,10 @@ class CompiledUrlMatcherDumperTest extends TestCase ->getMock(); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Symfony\Component\Routing\Route cannot contain objects - */ public function testGenerateDumperMatcherWithObject() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Symfony\Component\Routing\Route cannot contain objects'); $routeCollection = new RouteCollection(); $routeCollection->add('_', new Route('/', [new \stdClass()])); $dumper = new CompiledUrlMatcherDumper($routeCollection); diff --git a/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php b/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php index 426958e07e..e3577045b8 100644 --- a/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php +++ b/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php @@ -11,12 +11,15 @@ namespace Symfony\Component\Routing\Tests\Matcher; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; class RedirectableUrlMatcherTest extends UrlMatcherTest { + use ForwardCompatTestTrait; + public function testMissingTrailingSlash() { $coll = new RouteCollection(); @@ -37,11 +40,9 @@ class RedirectableUrlMatcherTest extends UrlMatcherTest $matcher->match('/foo/'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testRedirectWhenNoSlashForNonSafeMethod() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo/')); diff --git a/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php b/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php index 3897ee4a65..4c9206a6fa 100644 --- a/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php +++ b/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php @@ -199,22 +199,19 @@ class UrlMatcherTest extends TestCase $this->assertEquals(['_route' => 'index', '_format' => 'xml'], $matcher->match('/index.xml')); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testShortPathDoesNotMatchImportantVariable() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); + $collection = new RouteCollection(); $collection->add('index', new Route('/index.{!_format}', ['_format' => 'xml'])); $this->getUrlMatcher($collection)->match('/index'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testTrailingEncodedNewlineIsNotOverlooked() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $collection = new RouteCollection(); $collection->add('foo', new Route('/foo')); @@ -361,11 +358,9 @@ class UrlMatcherTest extends TestCase $this->assertEquals(['page' => 'index', '_format' => 'mobile.html', '_route' => 'test'], $matcher->match('/index.mobile.html')); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testDefaultRequirementOfVariableDisallowsSlash() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('test', new Route('/{page}.{_format}')); $matcher = $this->getUrlMatcher($coll); @@ -373,11 +368,9 @@ class UrlMatcherTest extends TestCase $matcher->match('/index.sl/ash'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testDefaultRequirementOfVariableDisallowsNextSeparator() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('test', new Route('/{page}.{_format}', [], ['_format' => 'html|xml'])); $matcher = $this->getUrlMatcher($coll); @@ -385,11 +378,9 @@ class UrlMatcherTest extends TestCase $matcher->match('/do.t.html'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testMissingTrailingSlash() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo/')); @@ -397,11 +388,9 @@ class UrlMatcherTest extends TestCase $matcher->match('/foo'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testExtraTrailingSlash() { + $this->getExpectedException() ?: $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo')); @@ -409,11 +398,9 @@ class UrlMatcherTest extends TestCase $matcher->match('/foo/'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testMissingTrailingSlashForNonSafeMethod() { + $this->getExpectedException() ?: $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo/')); @@ -423,11 +410,9 @@ class UrlMatcherTest extends TestCase $matcher->match('/foo'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testExtraTrailingSlashForNonSafeMethod() { + $this->getExpectedException() ?: $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo')); @@ -437,22 +422,18 @@ class UrlMatcherTest extends TestCase $matcher->match('/foo/'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testSchemeRequirement() { + $this->getExpectedException() ?: $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo', [], [], [], '', ['https'])); $matcher = $this->getUrlMatcher($coll); $matcher->match('/foo'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testSchemeRequirementForNonSafeMethod() { + $this->getExpectedException() ?: $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo', [], [], [], '', ['https'])); @@ -471,11 +452,9 @@ class UrlMatcherTest extends TestCase $this->assertEquals(['_route' => 'http_route'], $matcher->match('/')); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testCondition() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $route = new Route('/foo'); $route->setCondition('context.getMethod() == "POST"'); @@ -680,11 +659,9 @@ class UrlMatcherTest extends TestCase $this->assertEquals(['foo' => 'foo', '_route' => 'bar'], $matcher->match('/foo')); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testWithOutHostHostDoesNotMatch() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo/{foo}', [], [], [], '{locale}.example.com')); @@ -692,11 +669,9 @@ class UrlMatcherTest extends TestCase $matcher->match('/foo/bar'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testPathIsCaseSensitive() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/locale', [], ['locale' => 'EN|FR|DE'])); @@ -713,11 +688,9 @@ class UrlMatcherTest extends TestCase $this->assertEquals(['_route' => 'foo', 'locale' => 'en'], $matcher->match('/')); } - /** - * @expectedException \Symfony\Component\Routing\Exception\NoConfigurationException - */ public function testNoConfiguration() { + $this->expectException('Symfony\Component\Routing\Exception\NoConfigurationException'); $coll = new RouteCollection(); $matcher = $this->getUrlMatcher($coll); @@ -748,12 +721,10 @@ class UrlMatcherTest extends TestCase $this->assertEquals(['_route' => 'buz'], $matcher->match('/prefix/buz')); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - * @expectedExceptionMessage No routes found for "/". - */ public function testSchemeAndMethodMismatch() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); + $this->expectExceptionMessage('No routes found for "/".'); $coll = new RouteCollection(); $coll->add('foo', new Route('/', [], [], [], null, ['https'], ['POST'])); diff --git a/src/Symfony/Component/Routing/Tests/RouteCollectionBuilderTest.php b/src/Symfony/Component/Routing/Tests/RouteCollectionBuilderTest.php index 11d9453e09..3ce024751c 100644 --- a/src/Symfony/Component/Routing/Tests/RouteCollectionBuilderTest.php +++ b/src/Symfony/Component/Routing/Tests/RouteCollectionBuilderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Routing\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Routing\Loader\YamlFileLoader; @@ -21,6 +22,8 @@ use Symfony\Component\Routing\RouteCollectionBuilder; class RouteCollectionBuilderTest extends TestCase { + use ForwardCompatTestTrait; + public function testImport() { $resolvedLoader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock(); @@ -75,11 +78,9 @@ class RouteCollectionBuilderTest extends TestCase $this->assertCount(1, $routeCollection->getResources()); } - /** - * @expectedException \BadMethodCallException - */ public function testImportWithoutLoaderThrowsException() { + $this->expectException('BadMethodCallException'); $collectionBuilder = new RouteCollectionBuilder(); $collectionBuilder->import('routing.yml'); } diff --git a/src/Symfony/Component/Routing/Tests/RouteCompilerTest.php b/src/Symfony/Component/Routing/Tests/RouteCompilerTest.php index 705b5a0616..2387619a05 100644 --- a/src/Symfony/Component/Routing/Tests/RouteCompilerTest.php +++ b/src/Symfony/Component/Routing/Tests/RouteCompilerTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Routing\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCompiler; class RouteCompilerTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider provideCompileData */ @@ -185,10 +188,10 @@ class RouteCompilerTest extends TestCase /** * @dataProvider provideCompileImplicitUtf8Data - * @expectedException \LogicException */ public function testCompileImplicitUtf8Data($name, $arguments, $prefix, $regex, $variables, $tokens, $deprecationType) { + $this->expectException('LogicException'); $r = new \ReflectionClass('Symfony\\Component\\Routing\\Route'); $route = $r->newInstanceArgs($arguments); @@ -242,41 +245,33 @@ class RouteCompilerTest extends TestCase ]; } - /** - * @expectedException \LogicException - */ public function testRouteWithSameVariableTwice() { + $this->expectException('LogicException'); $route = new Route('/{name}/{name}'); $compiled = $route->compile(); } - /** - * @expectedException \LogicException - */ public function testRouteCharsetMismatch() { + $this->expectException('LogicException'); $route = new Route("/\xE9/{bar}", [], ['bar' => '.'], ['utf8' => true]); $compiled = $route->compile(); } - /** - * @expectedException \LogicException - */ public function testRequirementCharsetMismatch() { + $this->expectException('LogicException'); $route = new Route('/foo/{bar}', [], ['bar' => "\xE9"], ['utf8' => true]); $compiled = $route->compile(); } - /** - * @expectedException \InvalidArgumentException - */ public function testRouteWithFragmentAsPathParameter() { + $this->expectException('InvalidArgumentException'); $route = new Route('/{_fragment}'); $compiled = $route->compile(); @@ -284,10 +279,10 @@ class RouteCompilerTest extends TestCase /** * @dataProvider getVariableNamesStartingWithADigit - * @expectedException \DomainException */ public function testRouteWithVariableNameStartingWithADigit($name) { + $this->expectException('DomainException'); $route = new Route('/{'.$name.'}'); $route->compile(); } @@ -372,11 +367,9 @@ class RouteCompilerTest extends TestCase ]; } - /** - * @expectedException \DomainException - */ public function testRouteWithTooLongVariableName() { + $this->expectException('DomainException'); $route = new Route(sprintf('/{%s}', str_repeat('a', RouteCompiler::VARIABLE_MAXIMUM_LENGTH + 1))); $route->compile(); } diff --git a/src/Symfony/Component/Routing/Tests/RouteTest.php b/src/Symfony/Component/Routing/Tests/RouteTest.php index 46edb55896..3963afd162 100644 --- a/src/Symfony/Component/Routing/Tests/RouteTest.php +++ b/src/Symfony/Component/Routing/Tests/RouteTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Routing\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Routing\Route; class RouteTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $route = new Route('/{foo}', ['foo' => 'bar'], ['foo' => '\d+'], ['foo' => 'bar'], '{locale}.example.com'); @@ -124,10 +127,10 @@ class RouteTest extends TestCase /** * @dataProvider getInvalidRequirements - * @expectedException \InvalidArgumentException */ public function testSetInvalidRequirement($req) { + $this->expectException('InvalidArgumentException'); $route = new Route('/{foo}'); $route->setRequirement('foo', $req); } diff --git a/src/Symfony/Component/Routing/Tests/RouterTest.php b/src/Symfony/Component/Routing/Tests/RouterTest.php index 55f09da4d4..fd6fafd719 100644 --- a/src/Symfony/Component/Routing/Tests/RouterTest.php +++ b/src/Symfony/Component/Routing/Tests/RouterTest.php @@ -44,12 +44,10 @@ class RouterTest extends TestCase $this->assertSame('ResourceType', $this->router->getOption('resource_type')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The Router does not support the following options: "option_foo", "option_bar" - */ public function testSetOptionsWithUnsupportedOptions() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The Router does not support the following options: "option_foo", "option_bar"'); $this->router->setOptions([ 'cache_dir' => './cache', 'option_foo' => true, @@ -65,21 +63,17 @@ class RouterTest extends TestCase $this->assertSame('./cache', $this->router->getOption('cache_dir')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The Router does not support the "option_foo" option - */ public function testSetOptionWithUnsupportedOption() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The Router does not support the "option_foo" option'); $this->router->setOption('option_foo', true); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The Router does not support the "option_foo" option - */ public function testGetOptionWithUnsupportedOption() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The Router does not support the "option_foo" option'); $this->router->getOption('option_foo', true); } diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationProviderManagerTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationProviderManagerTest.php index deb05918f4..2fd9217395 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationProviderManagerTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationProviderManagerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Core\Tests\Authentication; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; @@ -24,19 +25,17 @@ use Symfony\Component\Security\Core\Exception\ProviderNotFoundException; class AuthenticationProviderManagerTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - */ + use ForwardCompatTestTrait; + public function testAuthenticateWithoutProviders() { + $this->expectException('InvalidArgumentException'); new AuthenticationProviderManager([]); } - /** - * @expectedException \InvalidArgumentException - */ public function testAuthenticateWithProvidersWithIncorrectInterface() { + $this->expectException('InvalidArgumentException'); (new AuthenticationProviderManager([ new \stdClass(), ]))->authenticate($this->getMockBuilder(TokenInterface::class)->getMock()); diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/AnonymousAuthenticationProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/AnonymousAuthenticationProviderTest.php index a888d2bf81..613d28382d 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/AnonymousAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/AnonymousAuthenticationProviderTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Security\Core\Tests\Authentication\Provider; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Authentication\Provider\AnonymousAuthenticationProvider; class AnonymousAuthenticationProviderTest extends TestCase { + use ForwardCompatTestTrait; + public function testSupports() { $provider = $this->getProvider('foo'); @@ -24,22 +27,18 @@ class AnonymousAuthenticationProviderTest extends TestCase $this->assertFalse($provider->supports($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock())); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationException - * @expectedExceptionMessage The token is not supported by this authentication provider. - */ public function testAuthenticateWhenTokenIsNotSupported() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException'); + $this->expectExceptionMessage('The token is not supported by this authentication provider.'); $provider = $this->getProvider('foo'); $provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testAuthenticateWhenSecretIsNotValid() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $provider = $this->getProvider('foo'); $provider->authenticate($this->getSupportedToken('bar')); diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/DaoAuthenticationProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/DaoAuthenticationProviderTest.php index 4949ce8a76..eca27b56af 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/DaoAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/DaoAuthenticationProviderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Core\Tests\Authentication\Provider; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider; use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; @@ -19,11 +20,11 @@ use Symfony\Component\Security\Core\User\UserInterface; class DaoAuthenticationProviderTest extends TestCase { - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException - */ + use ForwardCompatTestTrait; + public function testRetrieveUserWhenProviderDoesNotReturnAnUserInterface() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationServiceException'); $provider = $this->getProvider('fabien'); $method = new \ReflectionMethod($provider, 'retrieveUser'); $method->setAccessible(true); @@ -31,11 +32,9 @@ class DaoAuthenticationProviderTest extends TestCase $method->invoke($provider, 'fabien', $this->getSupportedToken()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException - */ public function testRetrieveUserWhenUsernameIsNotFound() { + $this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException'); $userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock(); $userProvider->expects($this->once()) ->method('loadUserByUsername') @@ -49,11 +48,9 @@ class DaoAuthenticationProviderTest extends TestCase $method->invoke($provider, 'fabien', $this->getSupportedToken()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException - */ public function testRetrieveUserWhenAnExceptionOccurs() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationServiceException'); $userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock(); $userProvider->expects($this->once()) ->method('loadUserByUsername') @@ -106,11 +103,9 @@ class DaoAuthenticationProviderTest extends TestCase $this->assertSame($user, $method->invoke($provider, 'fabien', $this->getSupportedToken())); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testCheckAuthenticationWhenCredentialsAreEmpty() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $encoder = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface')->getMock(); $encoder ->expects($this->never()) @@ -154,11 +149,9 @@ class DaoAuthenticationProviderTest extends TestCase $method->invoke($provider, new TestUser(), $token); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testCheckAuthenticationWhenCredentialsAreNotValid() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $encoder = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface')->getMock(); $encoder->expects($this->once()) ->method('isPasswordValid') @@ -178,11 +171,9 @@ class DaoAuthenticationProviderTest extends TestCase $method->invoke($provider, new TestUser(), $token); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testCheckAuthenticationDoesNotReauthenticateWhenPasswordHasChanged() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $user = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock(); $user->expects($this->once()) ->method('getPassword') diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/LdapBindAuthenticationProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/LdapBindAuthenticationProviderTest.php index 438b575cc9..fadaa75aa7 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/LdapBindAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/LdapBindAuthenticationProviderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Core\Tests\Authentication\Provider; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Ldap\Adapter\CollectionInterface; use Symfony\Component\Ldap\Adapter\QueryInterface; use Symfony\Component\Ldap\Entry; @@ -28,12 +29,12 @@ use Symfony\Component\Security\Core\User\UserProviderInterface; */ class LdapBindAuthenticationProviderTest extends TestCase { - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - * @expectedExceptionMessage The presented password must not be empty. - */ + use ForwardCompatTestTrait; + public function testEmptyPasswordShouldThrowAnException() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); + $this->expectExceptionMessage('The presented password must not be empty.'); $userProvider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock(); $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); $userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock(); @@ -45,12 +46,10 @@ class LdapBindAuthenticationProviderTest extends TestCase $reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', '', 'key')); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - * @expectedExceptionMessage The presented password must not be empty. - */ public function testNullPasswordShouldThrowAnException() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); + $this->expectExceptionMessage('The presented password must not be empty.'); $userProvider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock(); $ldap = $this->getMockBuilder('Symfony\Component\Ldap\LdapInterface')->getMock(); $userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock(); @@ -62,12 +61,10 @@ class LdapBindAuthenticationProviderTest extends TestCase $reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', null, 'key')); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - * @expectedExceptionMessage The presented password is invalid. - */ public function testBindFailureShouldThrowAnException() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); + $this->expectExceptionMessage('The presented password is invalid.'); $userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock(); $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); $ldap @@ -184,12 +181,10 @@ class LdapBindAuthenticationProviderTest extends TestCase $reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', 'bar', 'key')); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - * @expectedExceptionMessage The presented username is invalid. - */ public function testEmptyQueryResultShouldThrowAnException() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); + $this->expectExceptionMessage('The presented username is invalid.'); $userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock(); $collection = $this->getMockBuilder(CollectionInterface::class)->getMock(); diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.php index 3e452cfed8..a79b380263 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Security\Core\Tests\Authentication\Provider; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Authentication\Provider\PreAuthenticatedAuthenticationProvider; use Symfony\Component\Security\Core\Exception\LockedException; class PreAuthenticatedAuthenticationProviderTest extends TestCase { + use ForwardCompatTestTrait; + public function testSupports() { $provider = $this->getProvider(); @@ -36,22 +39,18 @@ class PreAuthenticatedAuthenticationProviderTest extends TestCase $this->assertFalse($provider->supports($token)); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationException - * @expectedExceptionMessage The token is not supported by this authentication provider. - */ public function testAuthenticateWhenTokenIsNotSupported() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException'); + $this->expectExceptionMessage('The token is not supported by this authentication provider.'); $provider = $this->getProvider(); $provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testAuthenticateWhenNoUserIsSet() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $provider = $this->getProvider(); $provider->authenticate($this->getSupportedToken('')); } @@ -75,11 +74,9 @@ class PreAuthenticatedAuthenticationProviderTest extends TestCase $this->assertSame($user, $token->getUser()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\LockedException - */ public function testAuthenticateWhenUserCheckerThrowsException() { + $this->expectException('Symfony\Component\Security\Core\Exception\LockedException'); $user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock(); $userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock(); diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/RememberMeAuthenticationProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/RememberMeAuthenticationProviderTest.php index da3129c0e0..eff06150b2 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/RememberMeAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/RememberMeAuthenticationProviderTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Security\Core\Tests\Authentication\Provider; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Authentication\Provider\RememberMeAuthenticationProvider; use Symfony\Component\Security\Core\Exception\DisabledException; class RememberMeAuthenticationProviderTest extends TestCase { + use ForwardCompatTestTrait; + public function testSupports() { $provider = $this->getProvider(); @@ -25,34 +28,28 @@ class RememberMeAuthenticationProviderTest extends TestCase $this->assertFalse($provider->supports($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock())); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationException - * @expectedExceptionMessage The token is not supported by this authentication provider. - */ public function testAuthenticateWhenTokenIsNotSupported() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException'); + $this->expectExceptionMessage('The token is not supported by this authentication provider.'); $provider = $this->getProvider(); $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock(); $provider->authenticate($token); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testAuthenticateWhenSecretsDoNotMatch() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $provider = $this->getProvider(null, 'secret1'); $token = $this->getSupportedToken(null, 'secret2'); $provider->authenticate($token); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\DisabledException - */ public function testAuthenticateWhenPreChecksFails() { + $this->expectException('Symfony\Component\Security\Core\Exception\DisabledException'); $userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock(); $userChecker->expects($this->once()) ->method('checkPreAuth') diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/UserAuthenticationProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/UserAuthenticationProviderTest.php index f00d71241e..d89ea088ba 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/UserAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Provider/UserAuthenticationProviderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Core\Tests\Authentication\Provider; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken; use Symfony\Component\Security\Core\Exception\AccountExpiredException; use Symfony\Component\Security\Core\Exception\BadCredentialsException; @@ -20,6 +21,8 @@ use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; class UserAuthenticationProviderTest extends TestCase { + use ForwardCompatTestTrait; + public function testSupports() { $provider = $this->getProvider(); @@ -28,22 +31,18 @@ class UserAuthenticationProviderTest extends TestCase $this->assertFalse($provider->supports($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock())); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationException - * @expectedExceptionMessage The token is not supported by this authentication provider. - */ public function testAuthenticateWhenTokenIsNotSupported() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException'); + $this->expectExceptionMessage('The token is not supported by this authentication provider.'); $provider = $this->getProvider(); $provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException - */ public function testAuthenticateWhenUsernameIsNotFound() { + $this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException'); $provider = $this->getProvider(false, false); $provider->expects($this->once()) ->method('retrieveUser') @@ -53,11 +52,9 @@ class UserAuthenticationProviderTest extends TestCase $provider->authenticate($this->getSupportedToken()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testAuthenticateWhenUsernameIsNotFoundAndHideIsTrue() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $provider = $this->getProvider(false, true); $provider->expects($this->once()) ->method('retrieveUser') @@ -67,11 +64,9 @@ class UserAuthenticationProviderTest extends TestCase $provider->authenticate($this->getSupportedToken()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException - */ public function testAuthenticateWhenProviderDoesNotReturnAnUserInterface() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationServiceException'); $provider = $this->getProvider(false, true); $provider->expects($this->once()) ->method('retrieveUser') @@ -81,11 +76,9 @@ class UserAuthenticationProviderTest extends TestCase $provider->authenticate($this->getSupportedToken()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\CredentialsExpiredException - */ public function testAuthenticateWhenPreChecksFails() { + $this->expectException('Symfony\Component\Security\Core\Exception\CredentialsExpiredException'); $userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock(); $userChecker->expects($this->once()) ->method('checkPreAuth') @@ -101,11 +94,9 @@ class UserAuthenticationProviderTest extends TestCase $provider->authenticate($this->getSupportedToken()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AccountExpiredException - */ public function testAuthenticateWhenPostChecksFails() { + $this->expectException('Symfony\Component\Security\Core\Exception\AccountExpiredException'); $userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock(); $userChecker->expects($this->once()) ->method('checkPostAuth') @@ -121,12 +112,10 @@ class UserAuthenticationProviderTest extends TestCase $provider->authenticate($this->getSupportedToken()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - * @expectedExceptionMessage Bad credentials - */ public function testAuthenticateWhenPostCheckAuthenticationFails() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); + $this->expectExceptionMessage('Bad credentials'); $provider = $this->getProvider(); $provider->expects($this->once()) ->method('retrieveUser') @@ -140,12 +129,10 @@ class UserAuthenticationProviderTest extends TestCase $provider->authenticate($this->getSupportedToken()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - * @expectedExceptionMessage Foo - */ public function testAuthenticateWhenPostCheckAuthenticationFailsWithHideFalse() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); + $this->expectExceptionMessage('Foo'); $provider = $this->getProvider(false, false); $provider->expects($this->once()) ->method('retrieveUser') diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.php index 1413b6d402..62ace03633 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Security\Core\Tests\Authentication\RememberMe; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Authentication\RememberMe\InMemoryTokenProvider; use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken; class InMemoryTokenProviderTest extends TestCase { + use ForwardCompatTestTrait; + public function testCreateNewToken() { $provider = new InMemoryTokenProvider(); @@ -27,11 +30,9 @@ class InMemoryTokenProviderTest extends TestCase $this->assertSame($provider->loadTokenBySeries('foo'), $token); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\TokenNotFoundException - */ public function testLoadTokenBySeriesThrowsNotFoundException() { + $this->expectException('Symfony\Component\Security\Core\Exception\TokenNotFoundException'); $provider = new InMemoryTokenProvider(); $provider->loadTokenBySeries('foo'); } @@ -49,11 +50,9 @@ class InMemoryTokenProviderTest extends TestCase $this->assertSame($token->getLastUsed(), $lastUsed); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\TokenNotFoundException - */ public function testDeleteToken() { + $this->expectException('Symfony\Component\Security\Core\Exception\TokenNotFoundException'); $provider = new InMemoryTokenProvider(); $token = new PersistentToken('foo', 'foo', 'foo', 'foo', new \DateTime()); diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Token/RememberMeTokenTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Token/RememberMeTokenTest.php index 4a56cf2881..5240d7bf21 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Token/RememberMeTokenTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Token/RememberMeTokenTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Security\Core\Tests\Authentication\Token; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken; class RememberMeTokenTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $user = $this->getUser(); @@ -28,11 +31,9 @@ class RememberMeTokenTest extends TestCase $this->assertTrue($token->isAuthenticated()); } - /** - * @expectedException \InvalidArgumentException - */ public function testConstructorSecretCannotBeEmptyString() { + $this->expectException('InvalidArgumentException'); new RememberMeToken( $this->getUser(), '', diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/Token/UsernamePasswordTokenTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/Token/UsernamePasswordTokenTest.php index ab0abaf653..acaadc07b6 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/Token/UsernamePasswordTokenTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/Token/UsernamePasswordTokenTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Security\Core\Tests\Authentication\Token; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; class UsernamePasswordTokenTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $token = new UsernamePasswordToken('foo', 'bar', 'key'); @@ -27,11 +30,9 @@ class UsernamePasswordTokenTest extends TestCase $this->assertEquals('key', $token->getProviderKey()); } - /** - * @expectedException \LogicException - */ public function testSetAuthenticatedToTrue() { + $this->expectException('LogicException'); $token = new UsernamePasswordToken('foo', 'bar', 'key'); $token->setAuthenticated(true); } diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.php index 690fcf70d5..5e6277dd6c 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.php @@ -20,11 +20,9 @@ class AccessDecisionManagerTest extends TestCase { use ForwardCompatTestTrait; - /** - * @expectedException \InvalidArgumentException - */ public function testSetUnsupportedStrategy() { + $this->expectException('InvalidArgumentException'); new AccessDecisionManager([$this->getVoter(VoterInterface::ACCESS_GRANTED)], 'fooBar'); } diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/AuthorizationCheckerTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/AuthorizationCheckerTest.php index 843f5783f8..4a60dae421 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/AuthorizationCheckerTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/AuthorizationCheckerTest.php @@ -70,11 +70,9 @@ class AuthorizationCheckerTest extends TestCase $this->assertSame($newToken, $this->tokenStorage->getToken()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException - */ public function testVoteWithoutAuthenticationToken() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException'); $this->authorizationChecker->isGranted('ROLE_FOO'); } diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.php index ae8467af57..5fc489e426 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Core\Tests\Encoder; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Encoder\EncoderAwareInterface; use Symfony\Component\Security\Core\Encoder\EncoderFactory; use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder; @@ -20,6 +21,8 @@ use Symfony\Component\Security\Core\User\UserInterface; class EncoderFactoryTest extends TestCase { + use ForwardCompatTestTrait; + public function testGetEncoderWithMessageDigestEncoder() { $factory = new EncoderFactory(['Symfony\Component\Security\Core\User\UserInterface' => [ @@ -107,11 +110,9 @@ class EncoderFactoryTest extends TestCase $this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', '')); } - /** - * @expectedException \RuntimeException - */ public function testGetInvalidNamedEncoderForEncoderAware() { + $this->expectException('RuntimeException'); $factory = new EncoderFactory([ 'Symfony\Component\Security\Core\Tests\Encoder\EncAwareUser' => new MessageDigestPasswordEncoder('sha1'), 'encoder_name' => new MessageDigestPasswordEncoder('sha256'), diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/MessageDigestPasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/MessageDigestPasswordEncoderTest.php index c449194f8d..50cd47bf0c 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/MessageDigestPasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/MessageDigestPasswordEncoderTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Security\Core\Tests\Encoder; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder; class MessageDigestPasswordEncoderTest extends TestCase { + use ForwardCompatTestTrait; + public function testIsPasswordValid() { $encoder = new MessageDigestPasswordEncoder('sha256', false, 1); @@ -35,20 +38,16 @@ class MessageDigestPasswordEncoderTest extends TestCase $this->assertSame(hash('sha256', hash('sha256', 'password', true).'password'), $encoder->encodePassword('password', '')); } - /** - * @expectedException \LogicException - */ public function testEncodePasswordAlgorithmDoesNotExist() { + $this->expectException('LogicException'); $encoder = new MessageDigestPasswordEncoder('foobar'); $encoder->encodePassword('password', ''); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testEncodePasswordLength() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $encoder = new MessageDigestPasswordEncoder(); $encoder->encodePassword(str_repeat('a', 5000), 'salt'); diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/NativePasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/NativePasswordEncoderTest.php index 55e518b491..ae65f99764 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/NativePasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/NativePasswordEncoderTest.php @@ -19,19 +19,15 @@ use Symfony\Component\Security\Core\Encoder\NativePasswordEncoder; */ class NativePasswordEncoderTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - */ public function testCostBelowRange() { + $this->expectException('InvalidArgumentException'); new NativePasswordEncoder(null, null, 3); } - /** - * @expectedException \InvalidArgumentException - */ public function testCostAboveRange() { + $this->expectException('InvalidArgumentException'); new NativePasswordEncoder(null, null, 32); } diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/Pbkdf2PasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/Pbkdf2PasswordEncoderTest.php index e65eef5bba..0795c4b5d6 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/Pbkdf2PasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/Pbkdf2PasswordEncoderTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Security\Core\Tests\Encoder; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Encoder\Pbkdf2PasswordEncoder; class Pbkdf2PasswordEncoderTest extends TestCase { + use ForwardCompatTestTrait; + public function testIsPasswordValid() { $encoder = new Pbkdf2PasswordEncoder('sha256', false, 1, 40); @@ -35,20 +38,16 @@ class Pbkdf2PasswordEncoderTest extends TestCase $this->assertSame('8bc2f9167a81cdcfad1235cd9047f1136271c1f978fcfcb35e22dbeafa4634f6fd2214218ed63ebb', $encoder->encodePassword('password', '')); } - /** - * @expectedException \LogicException - */ public function testEncodePasswordAlgorithmDoesNotExist() { + $this->expectException('LogicException'); $encoder = new Pbkdf2PasswordEncoder('foobar'); $encoder->encodePassword('password', ''); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testEncodePasswordLength() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $encoder = new Pbkdf2PasswordEncoder('foobar'); $encoder->encodePassword(str_repeat('a', 5000), 'salt'); diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/PlaintextPasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/PlaintextPasswordEncoderTest.php index 1196651a86..1ef0e0c778 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/PlaintextPasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/PlaintextPasswordEncoderTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Security\Core\Tests\Encoder; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder; class PlaintextPasswordEncoderTest extends TestCase { + use ForwardCompatTestTrait; + public function testIsPasswordValid() { $encoder = new PlaintextPasswordEncoder(); @@ -38,11 +41,9 @@ class PlaintextPasswordEncoderTest extends TestCase $this->assertSame('foo', $encoder->encodePassword('foo', '')); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testEncodePasswordLength() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $encoder = new PlaintextPasswordEncoder(); $encoder->encodePassword(str_repeat('a', 5000), 'salt'); diff --git a/src/Symfony/Component/Security/Core/Tests/Encoder/SodiumPasswordEncoderTest.php b/src/Symfony/Component/Security/Core/Tests/Encoder/SodiumPasswordEncoderTest.php index cb0b336905..9075fc4e8a 100644 --- a/src/Symfony/Component/Security/Core/Tests/Encoder/SodiumPasswordEncoderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Encoder/SodiumPasswordEncoderTest.php @@ -37,11 +37,9 @@ class SodiumPasswordEncoderTest extends TestCase $this->assertTrue($encoder->isPasswordValid('$2y$04$M8GDODMoGQLQRpkYCdoJh.lbiZPee3SZI32RcYK49XYTolDGwoRMm', 'abc', null)); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testEncodePasswordLength() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $encoder = new SodiumPasswordEncoder(); $encoder->encodePassword(str_repeat('a', 4097), 'salt'); } diff --git a/src/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.php b/src/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.php index 05a7fbba19..6852273aef 100644 --- a/src/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.php @@ -12,12 +12,15 @@ namespace Symfony\Component\Security\Core\Tests\User; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\User\ChainUserProvider; class ChainUserProviderTest extends TestCase { + use ForwardCompatTestTrait; + public function testLoadUserByUsername() { $provider1 = $this->getProvider(); @@ -40,11 +43,9 @@ class ChainUserProviderTest extends TestCase $this->assertSame($account, $provider->loadUserByUsername('foo')); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException - */ public function testLoadUserByUsernameThrowsUsernameNotFoundException() { + $this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException'); $provider1 = $this->getProvider(); $provider1 ->expects($this->once()) @@ -105,11 +106,9 @@ class ChainUserProviderTest extends TestCase $this->assertSame($account, $provider->refreshUser($this->getAccount())); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\UnsupportedUserException - */ public function testRefreshUserThrowsUnsupportedUserException() { + $this->expectException('Symfony\Component\Security\Core\Exception\UnsupportedUserException'); $provider1 = $this->getProvider(); $provider1 ->expects($this->once()) diff --git a/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserProviderTest.php b/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserProviderTest.php index b1ff3b66e1..6b78260b09 100644 --- a/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserProviderTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Security\Core\Tests\User; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\User\InMemoryUserProvider; use Symfony\Component\Security\Core\User\User; class InMemoryUserProviderTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $provider = $this->createProvider(); @@ -63,21 +66,17 @@ class InMemoryUserProviderTest extends TestCase $this->assertEquals('foo', $user->getPassword()); } - /** - * @expectedException \LogicException - */ public function testCreateUserAlreadyExist() { + $this->expectException('LogicException'); $provider = new InMemoryUserProvider(); $provider->createUser(new User('fabien', 'foo')); $provider->createUser(new User('fabien', 'foo')); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException - */ public function testLoadUserByUsernameDoesNotExist() { + $this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException'); $provider = new InMemoryUserProvider(); $provider->loadUserByUsername('fabien'); } diff --git a/src/Symfony/Component/Security/Core/Tests/User/LdapUserProviderTest.php b/src/Symfony/Component/Security/Core/Tests/User/LdapUserProviderTest.php index bca36c7b7f..c232e96e01 100644 --- a/src/Symfony/Component/Security/Core/Tests/User/LdapUserProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/User/LdapUserProviderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Core\Tests\User; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Ldap\Adapter\CollectionInterface; use Symfony\Component\Ldap\Adapter\QueryInterface; use Symfony\Component\Ldap\Entry; @@ -24,11 +25,11 @@ use Symfony\Component\Security\Core\User\LdapUserProvider; */ class LdapUserProviderTest extends TestCase { - /** - * @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException - */ + use ForwardCompatTestTrait; + public function testLoadUserByUsernameFailsIfCantConnectToLdap() { + $this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException'); $ldap = $this->getMockBuilder(LdapInterface::class)->getMock(); $ldap ->expects($this->once()) @@ -40,11 +41,9 @@ class LdapUserProviderTest extends TestCase $provider->loadUserByUsername('foo'); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException - */ public function testLoadUserByUsernameFailsIfNoLdapEntries() { + $this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException'); $result = $this->getMockBuilder(CollectionInterface::class)->getMock(); $query = $this->getMockBuilder(QueryInterface::class)->getMock(); $query @@ -73,11 +72,9 @@ class LdapUserProviderTest extends TestCase $provider->loadUserByUsername('foo'); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException - */ public function testLoadUserByUsernameFailsIfMoreThanOneLdapEntry() { + $this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException'); $result = $this->getMockBuilder(CollectionInterface::class)->getMock(); $query = $this->getMockBuilder(QueryInterface::class)->getMock(); $query @@ -106,11 +103,9 @@ class LdapUserProviderTest extends TestCase $provider->loadUserByUsername('foo'); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\InvalidArgumentException - */ public function testLoadUserByUsernameFailsIfMoreThanOneLdapPasswordsInEntry() { + $this->expectException('Symfony\Component\Security\Core\Exception\InvalidArgumentException'); $result = $this->getMockBuilder(CollectionInterface::class)->getMock(); $query = $this->getMockBuilder(QueryInterface::class)->getMock(); $query @@ -191,11 +186,9 @@ class LdapUserProviderTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\InvalidArgumentException - */ public function testLoadUserByUsernameFailsIfEntryHasNoPasswordAttribute() { + $this->expectException('Symfony\Component\Security\Core\Exception\InvalidArgumentException'); $result = $this->getMockBuilder(CollectionInterface::class)->getMock(); $query = $this->getMockBuilder(QueryInterface::class)->getMock(); $query diff --git a/src/Symfony/Component/Security/Core/Tests/User/UserCheckerTest.php b/src/Symfony/Component/Security/Core/Tests/User/UserCheckerTest.php index b7eeaea0db..774d5015f1 100644 --- a/src/Symfony/Component/Security/Core/Tests/User/UserCheckerTest.php +++ b/src/Symfony/Component/Security/Core/Tests/User/UserCheckerTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Security\Core\Tests\User; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\User\User; use Symfony\Component\Security\Core\User\UserChecker; class UserCheckerTest extends TestCase { + use ForwardCompatTestTrait; + public function testCheckPostAuthNotAdvancedUserInterface() { $checker = new UserChecker(); @@ -30,38 +33,30 @@ class UserCheckerTest extends TestCase $this->assertNull($checker->checkPostAuth(new User('John', 'password'))); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\CredentialsExpiredException - */ public function testCheckPostAuthCredentialsExpired() { + $this->expectException('Symfony\Component\Security\Core\Exception\CredentialsExpiredException'); $checker = new UserChecker(); $checker->checkPostAuth(new User('John', 'password', [], true, true, false, true)); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\LockedException - */ public function testCheckPreAuthAccountLocked() { + $this->expectException('Symfony\Component\Security\Core\Exception\LockedException'); $checker = new UserChecker(); $checker->checkPreAuth(new User('John', 'password', [], true, true, false, false)); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\DisabledException - */ public function testCheckPreAuthDisabled() { + $this->expectException('Symfony\Component\Security\Core\Exception\DisabledException'); $checker = new UserChecker(); $checker->checkPreAuth(new User('John', 'password', [], false, true, false, true)); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AccountExpiredException - */ public function testCheckPreAuthAccountExpired() { + $this->expectException('Symfony\Component\Security\Core\Exception\AccountExpiredException'); $checker = new UserChecker(); $checker->checkPreAuth(new User('John', 'password', [], true, false, true, true)); } diff --git a/src/Symfony/Component/Security/Core/Tests/User/UserTest.php b/src/Symfony/Component/Security/Core/Tests/User/UserTest.php index e132d01660..b4ed713a22 100644 --- a/src/Symfony/Component/Security/Core/Tests/User/UserTest.php +++ b/src/Symfony/Component/Security/Core/Tests/User/UserTest.php @@ -12,17 +12,18 @@ namespace Symfony\Component\Security\Core\Tests\User; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Core\User\EquatableInterface; use Symfony\Component\Security\Core\User\User; use Symfony\Component\Security\Core\User\UserInterface; class UserTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - */ + use ForwardCompatTestTrait; + public function testConstructorException() { + $this->expectException('InvalidArgumentException'); new User('', 'superpass'); } diff --git a/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php b/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php index 131b7f3b1f..c10011ac24 100644 --- a/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php @@ -115,11 +115,9 @@ abstract class UserPasswordValidatorTest extends ConstraintValidatorTestCase ]; } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testUserIsNotValid() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $user = $this->getMockBuilder('Foo\Bar\User')->getMock(); $this->tokenStorage = $this->createTokenStorage($user); diff --git a/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.php b/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.php index ac4c19b895..7574635dd4 100644 --- a/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.php +++ b/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.php @@ -89,11 +89,9 @@ class NativeSessionTokenStorageTest extends TestCase $this->assertSame('TOKEN', $this->storage->getToken('token_id')); } - /** - * @expectedException \Symfony\Component\Security\Csrf\Exception\TokenNotFoundException - */ public function testGetNonExistingToken() { + $this->expectException('Symfony\Component\Security\Csrf\Exception\TokenNotFoundException'); $this->storage->getToken('token_id'); } diff --git a/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.php b/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.php index d90278b16a..4ad0e08640 100644 --- a/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.php +++ b/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.php @@ -89,19 +89,15 @@ class SessionTokenStorageTest extends TestCase $this->assertSame('RESULT', $this->storage->getToken('token_id')); } - /** - * @expectedException \Symfony\Component\Security\Csrf\Exception\TokenNotFoundException - */ public function testGetNonExistingTokenFromClosedSession() { + $this->expectException('Symfony\Component\Security\Csrf\Exception\TokenNotFoundException'); $this->storage->getToken('token_id'); } - /** - * @expectedException \Symfony\Component\Security\Csrf\Exception\TokenNotFoundException - */ public function testGetNonExistingTokenFromActiveSession() { + $this->expectException('Symfony\Component\Security\Csrf\Exception\TokenNotFoundException'); $this->session->start(); $this->storage->getToken('token_id'); } diff --git a/src/Symfony/Component/Security/Guard/Tests/Firewall/GuardAuthenticationListenerTest.php b/src/Symfony/Component/Security/Guard/Tests/Firewall/GuardAuthenticationListenerTest.php index 7b27af093a..3e7b06d842 100644 --- a/src/Symfony/Component/Security/Guard/Tests/Firewall/GuardAuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Guard/Tests/Firewall/GuardAuthenticationListenerTest.php @@ -235,11 +235,9 @@ class GuardAuthenticationListenerTest extends TestCase $listener($this->event); } - /** - * @expectedException \UnexpectedValueException - */ public function testReturnNullFromGetCredentials() { + $this->expectException('UnexpectedValueException'); $authenticator = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); $providerKey = 'my_firewall4'; diff --git a/src/Symfony/Component/Security/Guard/Tests/Provider/GuardAuthenticationProviderTest.php b/src/Symfony/Component/Security/Guard/Tests/Provider/GuardAuthenticationProviderTest.php index 5efca595fc..92262bcdab 100644 --- a/src/Symfony/Component/Security/Guard/Tests/Provider/GuardAuthenticationProviderTest.php +++ b/src/Symfony/Component/Security/Guard/Tests/Provider/GuardAuthenticationProviderTest.php @@ -90,11 +90,9 @@ class GuardAuthenticationProviderTest extends TestCase $this->assertSame($authedToken, $actualAuthedToken); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testCheckCredentialsReturningNonTrueFailsAuthentication() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $providerKey = 'my_uncool_firewall'; $authenticator = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); @@ -123,11 +121,9 @@ class GuardAuthenticationProviderTest extends TestCase $provider->authenticate($this->preAuthenticationToken); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationExpiredException - */ public function testGuardWithNoLongerAuthenticatedTriggersLogout() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationExpiredException'); $providerKey = 'my_firewall_abc'; // create a token and mark it as NOT authenticated anymore @@ -158,12 +154,10 @@ class GuardAuthenticationProviderTest extends TestCase $this->assertFalse($supports); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationException - * @expectedExceptionMessageRegExp /second_firewall_0/ - */ public function testAuthenticateFailsOnNonOriginatingToken() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException'); + $this->expectExceptionMessageRegExp('/second_firewall_0/'); $authenticatorA = $this->getMockBuilder(AuthenticatorInterface::class)->getMock(); $authenticators = [$authenticatorA]; diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.php index e0f4304e03..ab549a597a 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.php @@ -12,16 +12,17 @@ namespace Symfony\Component\Security\Http\Tests\Firewall; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\Security\Http\Firewall\AccessListener; class AccessListenerTest extends TestCase { - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException - */ + use ForwardCompatTestTrait; + public function testHandleWhenTheAccessDecisionManagerDecidesToRefuseAccess() { + $this->expectException('Symfony\Component\Security\Core\Exception\AccessDeniedException'); $request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock(); $accessMap = $this->getMockBuilder('Symfony\Component\Security\Http\AccessMapInterface')->getMock(); @@ -184,11 +185,9 @@ class AccessListenerTest extends TestCase $listener($event); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException - */ public function testHandleWhenTheSecurityTokenStorageHasNoToken() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException'); $tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(); $tokenStorage ->expects($this->any()) diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/BasicAuthenticationListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/BasicAuthenticationListenerTest.php index 7a62671431..0a03f825cb 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/BasicAuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/BasicAuthenticationListenerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Http\Tests\Firewall; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\RequestEvent; @@ -22,6 +23,8 @@ use Symfony\Component\Security\Http\Firewall\BasicAuthenticationListener; class BasicAuthenticationListenerTest extends TestCase { + use ForwardCompatTestTrait; + public function testHandleWithValidUsernameAndPasswordServerParameters() { $request = new Request([], [], [], [], [], [ @@ -183,12 +186,10 @@ class BasicAuthenticationListenerTest extends TestCase $listener($event); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage $providerKey must not be empty - */ public function testItRequiresProviderKey() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('$providerKey must not be empty'); new BasicAuthenticationListener( $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(), $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(), diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/ContextListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/ContextListenerTest.php index 74c37d42fc..4bd56c911b 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/ContextListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/ContextListenerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Http\Tests\Firewall; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; @@ -36,12 +37,12 @@ use Symfony\Component\Security\Http\Firewall\ContextListener; class ContextListenerTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage $contextKey must not be empty - */ + use ForwardCompatTestTrait; + public function testItRequiresContextKey() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('$contextKey must not be empty'); new ContextListener( $this->getMockBuilder(TokenStorageInterface::class)->getMock(), [], @@ -49,12 +50,10 @@ class ContextListenerTest extends TestCase ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage User provider "stdClass" must implement "Symfony\Component\Security\Core\User\UserProviderInterface - */ public function testUserProvidersNeedToImplementAnInterface() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('User provider "stdClass" must implement "Symfony\Component\Security\Core\User\UserProviderInterface'); $this->handleEventWithPreviousSession(new TokenStorage(), [new \stdClass()]); } @@ -297,11 +296,9 @@ class ContextListenerTest extends TestCase $this->assertNull($tokenStorage->getToken()); } - /** - * @expectedException \RuntimeException - */ public function testRuntimeExceptionIsThrownIfNoSupportingUserProviderWasRegistered() { + $this->expectException('RuntimeException'); $this->handleEventWithPreviousSession(new TokenStorage(), [new NotSupportingUserProvider(), new NotSupportingUserProvider()]); } diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.php index b68888ef77..64ad404a7a 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Http\Tests\Firewall; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\RequestEvent; @@ -19,6 +20,8 @@ use Symfony\Component\Security\Http\Firewall\LogoutListener; class LogoutListenerTest extends TestCase { + use ForwardCompatTestTrait; + public function testHandleUnmatchedPath() { list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener(); @@ -123,11 +126,9 @@ class LogoutListenerTest extends TestCase $listener($event); } - /** - * @expectedException \RuntimeException - */ public function testSuccessHandlerReturnsNonResponse() { + $this->expectException('RuntimeException'); $successHandler = $this->getSuccessHandler(); list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener($successHandler); @@ -147,11 +148,9 @@ class LogoutListenerTest extends TestCase $listener($event); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\LogoutException - */ public function testCsrfValidationFails() { + $this->expectException('Symfony\Component\Security\Core\Exception\LogoutException'); $tokenManager = $this->getTokenManager(); list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener(null, $tokenManager); diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/RememberMeListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/RememberMeListenerTest.php index 850f88c61c..8ca2ec24ea 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/RememberMeListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/RememberMeListenerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Http\Tests\Firewall; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\Event\ResponseEvent; @@ -22,6 +23,8 @@ use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; class RememberMeListenerTest extends TestCase { + use ForwardCompatTestTrait; + public function testOnCoreSecurityDoesNotTryToPopulateNonEmptyTokenStorage() { list($listener, $tokenStorage) = $this->getListener(); @@ -106,12 +109,10 @@ class RememberMeListenerTest extends TestCase $listener($event); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationException - * @expectedExceptionMessage Authentication failed. - */ public function testOnCoreSecurityIgnoresAuthenticationOptionallyRethrowsExceptionThrownAuthenticationManagerImplementation() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException'); + $this->expectExceptionMessage('Authentication failed.'); list($listener, $tokenStorage, $service, $manager) = $this->getListener(false, false); $tokenStorage diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/RemoteUserAuthenticationListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/RemoteUserAuthenticationListenerTest.php index ee5334c1e7..6328ddf523 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/RemoteUserAuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/RemoteUserAuthenticationListenerTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Security\Http\Tests\Firewall; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Http\Firewall\RemoteUserAuthenticationListener; class RemoteUserAuthenticationListenerTest extends TestCase { + use ForwardCompatTestTrait; + public function testGetPreAuthenticatedData() { $serverVars = [ @@ -42,11 +45,9 @@ class RemoteUserAuthenticationListenerTest extends TestCase $this->assertSame($result, ['TheUser', null]); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testGetPreAuthenticatedDataNoUser() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $request = new Request([], [], [], [], [], []); $tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(); diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php index 43696475aa..3a233aa689 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php @@ -51,12 +51,10 @@ class SwitchUserListenerTest extends TestCase $this->event = new RequestEvent($this->getMockBuilder(HttpKernelInterface::class)->getMock(), $this->request, HttpKernelInterface::MASTER_REQUEST); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage $providerKey must not be empty - */ public function testProviderKeyIsRequired() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('$providerKey must not be empty'); new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, '', $this->accessDecisionManager); } @@ -69,22 +67,18 @@ class SwitchUserListenerTest extends TestCase $this->assertNull($this->tokenStorage->getToken()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException - */ public function testExitUserThrowsAuthenticationExceptionIfNoCurrentToken() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException'); $this->tokenStorage->setToken(null); $this->request->query->set('_switch_user', '_exit'); $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager); $listener($this->event); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException - */ public function testExitUserThrowsAuthenticationExceptionIfOriginalTokenCannotBeFound() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException'); $token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']); $this->tokenStorage->setToken($token); @@ -162,11 +156,9 @@ class SwitchUserListenerTest extends TestCase $listener($this->event); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException - */ public function testSwitchUserIsDisallowed() { + $this->expectException('Symfony\Component\Security\Core\Exception\AccessDeniedException'); $token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']); $this->tokenStorage->setToken($token); @@ -276,11 +268,9 @@ class SwitchUserListenerTest extends TestCase $this->assertSame($replacedToken, $this->tokenStorage->getToken()); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException - */ public function testSwitchtUserThrowsAuthenticationExceptionIfNoCurrentToken() { + $this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException'); $this->tokenStorage->setToken(null); $this->request->query->set('_switch_user', 'username'); $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager); diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordFormAuthenticationListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordFormAuthenticationListenerTest.php index 6fc4b07ea8..a93377d308 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordFormAuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordFormAuthenticationListenerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Tests\Http\Firewall; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\RequestEvent; @@ -26,6 +27,8 @@ use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy; class UsernamePasswordFormAuthenticationListenerTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getUsernameForLength */ @@ -78,11 +81,11 @@ class UsernamePasswordFormAuthenticationListenerTest extends TestCase /** * @dataProvider postOnlyDataProvider - * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException - * @expectedExceptionMessage The key "_username" must be a string, "array" given. */ public function testHandleNonStringUsernameWithArray($postOnly) { + $this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException'); + $this->expectExceptionMessage('The key "_username" must be a string, "array" given.'); $request = Request::create('/login_check', 'POST', ['_username' => []]); $request->setSession($this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock()); $listener = new UsernamePasswordFormAuthenticationListener( @@ -101,11 +104,11 @@ class UsernamePasswordFormAuthenticationListenerTest extends TestCase /** * @dataProvider postOnlyDataProvider - * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException - * @expectedExceptionMessage The key "_username" must be a string, "integer" given. */ public function testHandleNonStringUsernameWithInt($postOnly) { + $this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException'); + $this->expectExceptionMessage('The key "_username" must be a string, "integer" given.'); $request = Request::create('/login_check', 'POST', ['_username' => 42]); $request->setSession($this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock()); $listener = new UsernamePasswordFormAuthenticationListener( @@ -124,11 +127,11 @@ class UsernamePasswordFormAuthenticationListenerTest extends TestCase /** * @dataProvider postOnlyDataProvider - * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException - * @expectedExceptionMessage The key "_username" must be a string, "object" given. */ public function testHandleNonStringUsernameWithObject($postOnly) { + $this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException'); + $this->expectExceptionMessage('The key "_username" must be a string, "object" given.'); $request = Request::create('/login_check', 'POST', ['_username' => new \stdClass()]); $request->setSession($this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock()); $listener = new UsernamePasswordFormAuthenticationListener( diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordJsonAuthenticationListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordJsonAuthenticationListenerTest.php index fb3227ce21..84d733b2b2 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordJsonAuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/UsernamePasswordJsonAuthenticationListenerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Tests\Http\Firewall; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\RequestEvent; @@ -31,6 +32,8 @@ use Symfony\Component\Security\Http\HttpUtils; */ class UsernamePasswordJsonAuthenticationListenerTest extends TestCase { + use ForwardCompatTestTrait; + /** * @var UsernamePasswordJsonAuthenticationListener */ @@ -104,12 +107,10 @@ class UsernamePasswordJsonAuthenticationListenerTest extends TestCase $this->assertEquals('ok', $event->getResponse()->getContent()); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException - * @expectedExceptionMessage Invalid JSON - */ public function testAttemptAuthenticationNoJson() { + $this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException'); + $this->expectExceptionMessage('Invalid JSON'); $this->createListener(); $request = new Request(); $request->setRequestFormat('json'); @@ -118,12 +119,10 @@ class UsernamePasswordJsonAuthenticationListenerTest extends TestCase ($this->listener)($event); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException - * @expectedExceptionMessage The key "username" must be provided - */ public function testAttemptAuthenticationNoUsername() { + $this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException'); + $this->expectExceptionMessage('The key "username" must be provided'); $this->createListener(); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"usr": "dunglas", "password": "foo"}'); $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); @@ -131,12 +130,10 @@ class UsernamePasswordJsonAuthenticationListenerTest extends TestCase ($this->listener)($event); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException - * @expectedExceptionMessage The key "password" must be provided - */ public function testAttemptAuthenticationNoPassword() { + $this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException'); + $this->expectExceptionMessage('The key "password" must be provided'); $this->createListener(); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "pass": "foo"}'); $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); @@ -144,12 +141,10 @@ class UsernamePasswordJsonAuthenticationListenerTest extends TestCase ($this->listener)($event); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException - * @expectedExceptionMessage The key "username" must be a string. - */ public function testAttemptAuthenticationUsernameNotAString() { + $this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException'); + $this->expectExceptionMessage('The key "username" must be a string.'); $this->createListener(); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": 1, "password": "foo"}'); $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); @@ -157,12 +152,10 @@ class UsernamePasswordJsonAuthenticationListenerTest extends TestCase ($this->listener)($event); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException - * @expectedExceptionMessage The key "password" must be a string. - */ public function testAttemptAuthenticationPasswordNotAString() { + $this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException'); + $this->expectExceptionMessage('The key "password" must be a string.'); $this->createListener(); $request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "password": 1}'); $event = new RequestEvent($this->getMockBuilder(KernelInterface::class)->getMock(), $request, KernelInterface::MASTER_REQUEST); diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/X509AuthenticationListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/X509AuthenticationListenerTest.php index 577ca7c38f..b82b616a63 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/X509AuthenticationListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/X509AuthenticationListenerTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Security\Http\Tests\Firewall; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Http\Firewall\X509AuthenticationListener; class X509AuthenticationListenerTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider dataProviderGetPreAuthenticatedData */ @@ -83,11 +86,9 @@ class X509AuthenticationListenerTest extends TestCase yield ['cert+something@example.com', 'emailAddress=cert+something@example.com']; } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException - */ public function testGetPreAuthenticatedDataNoData() { + $this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException'); $request = new Request([], [], [], [], [], []); $tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(); diff --git a/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php b/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php index a4a76747e5..016a22655a 100644 --- a/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php +++ b/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Security\Http\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Exception\ResourceNotFoundException; @@ -21,6 +22,8 @@ use Symfony\Component\Security\Http\HttpUtils; class HttpUtilsTest extends TestCase { + use ForwardCompatTestTrait; + public function testCreateRedirectResponseWithPath() { $utils = new HttpUtils($this->getUrlGenerator()); @@ -251,11 +254,9 @@ class HttpUtilsTest extends TestCase $this->assertTrue($utils->checkRequestPath($request, 'foobar')); } - /** - * @expectedException \RuntimeException - */ public function testCheckRequestPathWithUrlMatcherLoadingException() { + $this->expectException('RuntimeException'); $urlMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\UrlMatcherInterface')->getMock(); $urlMatcher ->expects($this->any()) @@ -280,12 +281,10 @@ class HttpUtilsTest extends TestCase $this->assertFalse($utils->checkRequestPath($this->getRequest(), 'path/index.html')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Matcher must either implement UrlMatcherInterface or RequestMatcherInterface - */ public function testUrlMatcher() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface'); new HttpUtils($this->getUrlGenerator(), new \stdClass()); } @@ -307,12 +306,10 @@ class HttpUtilsTest extends TestCase $this->assertEquals('/foo/bar#fragment', $utils->generateUri(new Request(), 'route_name')); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage You must provide a UrlGeneratorInterface instance to be able to use routes. - */ public function testUrlGeneratorIsRequiredToGenerateUrl() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('You must provide a UrlGeneratorInterface instance to be able to use routes.'); $utils = new HttpUtils(); $utils->generateUri(new Request(), 'route_name'); } diff --git a/src/Symfony/Component/Security/Http/Tests/Logout/LogoutUrlGeneratorTest.php b/src/Symfony/Component/Security/Http/Tests/Logout/LogoutUrlGeneratorTest.php index 8cf3da687f..f2e0154d92 100644 --- a/src/Symfony/Component/Security/Http/Tests/Logout/LogoutUrlGeneratorTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Logout/LogoutUrlGeneratorTest.php @@ -49,12 +49,10 @@ class LogoutUrlGeneratorTest extends TestCase $this->assertSame('/logout', $this->generator->getLogoutPath('secured_area')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage No LogoutListener found for firewall key "unregistered_key". - */ public function testGetLogoutPathWithoutLogoutListenerRegisteredForKeyThrowsException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('No LogoutListener found for firewall key "unregistered_key".'); $this->generator->registerListener('secured_area', '/logout', null, null, null); $this->generator->getLogoutPath('unregistered_key'); @@ -68,12 +66,10 @@ class LogoutUrlGeneratorTest extends TestCase $this->assertSame('/logout', $this->generator->getLogoutPath()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Unable to generate a logout url for an anonymous token. - */ public function testGuessFromAnonymousTokenThrowsException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Unable to generate a logout url for an anonymous token.'); $this->tokenStorage->setToken(new AnonymousToken('default', 'anon.')); $this->generator->getLogoutPath(); @@ -104,12 +100,10 @@ class LogoutUrlGeneratorTest extends TestCase $this->assertSame('/logout', $this->generator->getLogoutPath()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Unable to find the current firewall LogoutListener, please provide the provider key manually - */ public function testUnableToGuessThrowsException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Unable to find the current firewall LogoutListener, please provide the provider key manually'); $this->generator->registerListener('secured_area', '/logout', null, null); $this->generator->getLogoutPath(); diff --git a/src/Symfony/Component/Security/Http/Tests/RememberMe/AbstractRememberMeServicesTest.php b/src/Symfony/Component/Security/Http/Tests/RememberMe/AbstractRememberMeServicesTest.php index 3709a92bba..0cf4654bcc 100644 --- a/src/Symfony/Component/Security/Http/Tests/RememberMe/AbstractRememberMeServicesTest.php +++ b/src/Symfony/Component/Security/Http/Tests/RememberMe/AbstractRememberMeServicesTest.php @@ -42,11 +42,9 @@ class AbstractRememberMeServicesTest extends TestCase $this->assertNull($service->autoLogin(new Request())); } - /** - * @expectedException \RuntimeException - */ public function testAutoLoginThrowsExceptionWhenImplementationDoesNotReturnUserInterface() { + $this->expectException('RuntimeException'); $service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null]); $request = new Request(); $request->cookies->set('foo', 'foo'); @@ -270,12 +268,10 @@ class AbstractRememberMeServicesTest extends TestCase $this->assertSame($cookieParts, $decoded); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage cookie delimiter - */ public function testThereShouldBeNoCookieDelimiterInCookieParts() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('cookie delimiter'); $cookieParts = ['aa', 'b'.AbstractRememberMeServices::COOKIE_DELIMITER.'b', 'cc']; $service = $this->getService(); diff --git a/src/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.php b/src/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.php index 6c0df8cb5f..4ef0b80b06 100644 --- a/src/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Security\Http\Tests\Session; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy; class SessionAuthenticationStrategyTest extends TestCase { + use ForwardCompatTestTrait; + public function testSessionIsNotChanged() { $request = $this->getRequest(); @@ -25,12 +28,10 @@ class SessionAuthenticationStrategyTest extends TestCase $strategy->onAuthentication($request, $this->getToken()); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Invalid session authentication strategy "foo" - */ public function testUnsupportedStrategy() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Invalid session authentication strategy "foo"'); $request = $this->getRequest(); $request->expects($this->never())->method('getSession'); diff --git a/src/Symfony/Component/Serializer/Tests/Annotation/DiscriminatorMapTest.php b/src/Symfony/Component/Serializer/Tests/Annotation/DiscriminatorMapTest.php index 3f3f166636..81f2db2cdd 100644 --- a/src/Symfony/Component/Serializer/Tests/Annotation/DiscriminatorMapTest.php +++ b/src/Symfony/Component/Serializer/Tests/Annotation/DiscriminatorMapTest.php @@ -33,35 +33,27 @@ class DiscriminatorMapTest extends TestCase ], $annotation->getMapping()); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - */ public function testExceptionWithoutTypeProperty() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); new DiscriminatorMap(['mapping' => ['foo' => 'FooClass']]); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - */ public function testExceptionWithEmptyTypeProperty() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); new DiscriminatorMap(['typeProperty' => '', 'mapping' => ['foo' => 'FooClass']]); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - */ public function testExceptionWithoutMappingProperty() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); new DiscriminatorMap(['typeProperty' => 'type']); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - */ public function testExceptionWitEmptyMappingProperty() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); new DiscriminatorMap(['typeProperty' => 'type', 'mapping' => []]); } } diff --git a/src/Symfony/Component/Serializer/Tests/Annotation/GroupsTest.php b/src/Symfony/Component/Serializer/Tests/Annotation/GroupsTest.php index 9b54221d76..203eb3c92b 100644 --- a/src/Symfony/Component/Serializer/Tests/Annotation/GroupsTest.php +++ b/src/Symfony/Component/Serializer/Tests/Annotation/GroupsTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Serializer\Tests\Annotation; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Serializer\Annotation\Groups; /** @@ -19,27 +20,23 @@ use Symfony\Component\Serializer\Annotation\Groups; */ class GroupsTest extends TestCase { - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - */ + use ForwardCompatTestTrait; + public function testEmptyGroupsParameter() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); new Groups(['value' => []]); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - */ public function testNotAnArrayGroupsParameter() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); new Groups(['value' => 12]); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - */ public function testInvalidGroupsParameter() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); new Groups(['value' => ['a', 1, new \stdClass()]]); } diff --git a/src/Symfony/Component/Serializer/Tests/Annotation/MaxDepthTest.php b/src/Symfony/Component/Serializer/Tests/Annotation/MaxDepthTest.php index 16f10e1434..8cca874ecd 100644 --- a/src/Symfony/Component/Serializer/Tests/Annotation/MaxDepthTest.php +++ b/src/Symfony/Component/Serializer/Tests/Annotation/MaxDepthTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Serializer\Tests\Annotation; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Serializer\Annotation\MaxDepth; /** @@ -19,12 +20,12 @@ use Symfony\Component\Serializer\Annotation\MaxDepth; */ class MaxDepthTest extends TestCase { - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - * @expectedExceptionMessage Parameter of annotation "Symfony\Component\Serializer\Annotation\MaxDepth" should be set. - */ + use ForwardCompatTestTrait; + public function testNotSetMaxDepthParameter() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Parameter of annotation "Symfony\Component\Serializer\Annotation\MaxDepth" should be set.'); new MaxDepth([]); } @@ -40,12 +41,11 @@ class MaxDepthTest extends TestCase /** * @dataProvider provideInvalidValues - * - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - * @expectedExceptionMessage Parameter of annotation "Symfony\Component\Serializer\Annotation\MaxDepth" must be a positive integer. */ public function testNotAnIntMaxDepthParameter($value) { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Parameter of annotation "Symfony\Component\Serializer\Annotation\MaxDepth" must be a positive integer.'); new MaxDepth(['value' => $value]); } diff --git a/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php b/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php index 1b6f4ff9f0..cb934580b0 100644 --- a/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php +++ b/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php @@ -19,12 +19,10 @@ use Symfony\Component\Serializer\Annotation\SerializedName; */ class SerializedNameTest extends TestCase { - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - * @expectedExceptionMessage Parameter of annotation "Symfony\Component\Serializer\Annotation\SerializedName" should be set. - */ public function testNotSetSerializedNameParameter() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Parameter of annotation "Symfony\Component\Serializer\Annotation\SerializedName" should be set.'); new SerializedName([]); } @@ -38,12 +36,11 @@ class SerializedNameTest extends TestCase /** * @dataProvider provideInvalidValues - * - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - * @expectedExceptionMessage Parameter of annotation "Symfony\Component\Serializer\Annotation\SerializedName" must be a non-empty string. */ public function testNotAStringSerializedNameParameter($value) { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Parameter of annotation "Symfony\Component\Serializer\Annotation\SerializedName" must be a non-empty string.'); new SerializedName(['value' => $value]); } diff --git a/src/Symfony/Component/Serializer/Tests/DependencyInjection/SerializerPassTest.php b/src/Symfony/Component/Serializer/Tests/DependencyInjection/SerializerPassTest.php index 5c3fedfe89..d5e044504f 100644 --- a/src/Symfony/Component/Serializer/Tests/DependencyInjection/SerializerPassTest.php +++ b/src/Symfony/Component/Serializer/Tests/DependencyInjection/SerializerPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Serializer\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\Serializer\DependencyInjection\SerializerPass; @@ -23,12 +24,12 @@ use Symfony\Component\Serializer\DependencyInjection\SerializerPass; */ class SerializerPassTest extends TestCase { - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage You must tag at least one service as "serializer.normalizer" to use the "serializer" service - */ + use ForwardCompatTestTrait; + public function testThrowExceptionWhenNoNormalizers() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('You must tag at least one service as "serializer.normalizer" to use the "serializer" service'); $container = new ContainerBuilder(); $container->register('serializer'); @@ -36,12 +37,10 @@ class SerializerPassTest extends TestCase $serializerPass->process($container); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage You must tag at least one service as "serializer.encoder" to use the "serializer" service - */ public function testThrowExceptionWhenNoEncoders() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('You must tag at least one service as "serializer.encoder" to use the "serializer" service'); $container = new ContainerBuilder(); $container->register('serializer') ->addArgument([]) diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/ChainDecoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/ChainDecoderTest.php index ecb37f2300..659930c41e 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/ChainDecoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/ChainDecoderTest.php @@ -73,11 +73,9 @@ class ChainDecoderTest extends TestCase $this->chainDecoder->decode('string_to_decode', self::FORMAT_2); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\RuntimeException - */ public function testDecodeUnsupportedFormat() { + $this->expectException('Symfony\Component\Serializer\Exception\RuntimeException'); $this->chainDecoder->decode('string_to_decode', self::FORMAT_3); } } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/ChainEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/ChainEncoderTest.php index 2a0f85d04a..bfec205a27 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/ChainEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/ChainEncoderTest.php @@ -75,11 +75,9 @@ class ChainEncoderTest extends TestCase $this->chainEncoder->encode(['foo' => 123], self::FORMAT_2); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\RuntimeException - */ public function testEncodeUnsupportedFormat() { + $this->expectException('Symfony\Component\Serializer\Exception\RuntimeException'); $this->chainEncoder->encode(['foo' => 123], self::FORMAT_3); } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/JsonDecodeTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/JsonDecodeTest.php index e10da56661..8ff1482eb5 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/JsonDecodeTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/JsonDecodeTest.php @@ -60,10 +60,10 @@ class JsonDecodeTest extends TestCase /** * @dataProvider decodeProviderException - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException */ public function testDecodeWithException($value) { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $this->decode->decode($value, JsonEncoder::FORMAT); } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncodeTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncodeTest.php index 72703f873f..68ea7da068 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncodeTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncodeTest.php @@ -52,11 +52,9 @@ class JsonEncodeTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testEncodeWithError() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $this->encode->encode("\xB1\x31", JsonEncoder::FORMAT); } } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php index 0080112baa..27e1a55b02 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php @@ -68,11 +68,9 @@ class JsonEncoderTest extends TestCase $this->assertEquals($expected, $this->serializer->serialize($arr, 'json'), 'Context should not be persistent'); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testEncodeNotUtf8WithoutPartialOnError() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $arr = [ 'utf8' => 'Hello World!', 'notUtf8' => "\xb0\xd0\xb5\xd0", diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php index f1284334d8..f4a1ea7458 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php @@ -50,12 +50,10 @@ class XmlEncoderTest extends TestCase $this->assertEquals($expected, $this->encoder->encode($obj, 'xml')); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - * @expectedExceptionMessage Document types are not allowed. - */ public function testDocTypeIsNotAllowed() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); + $this->expectExceptionMessage('Document types are not allowed.'); $this->encoder->decode('', 'foo'); } @@ -636,19 +634,15 @@ XML; $this->assertEquals($expected, $this->encoder->decode($xml, 'xml')); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testDecodeInvalidXml() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $this->encoder->decode('', 'xml'); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testPreventsComplexExternalEntities() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $this->encoder->decode(']>&test;', 'xml'); } diff --git a/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CacheMetadataFactoryTest.php b/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CacheMetadataFactoryTest.php index 067f16acf9..8c5d61e261 100644 --- a/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CacheMetadataFactoryTest.php +++ b/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CacheMetadataFactoryTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Serializer\Tests\Mapping\Factory; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Serializer\Mapping\ClassMetadata; use Symfony\Component\Serializer\Mapping\Factory\CacheClassMetadataFactory; @@ -23,6 +24,8 @@ use Symfony\Component\Serializer\Tests\Fixtures\Dummy; */ class CacheMetadataFactoryTest extends TestCase { + use ForwardCompatTestTrait; + public function testGetMetadataFor() { $metadata = new ClassMetadata(Dummy::class); @@ -55,11 +58,9 @@ class CacheMetadataFactoryTest extends TestCase $this->assertTrue($factory->hasMetadataFor(Dummy::class)); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - */ public function testInvalidClassThrowsException() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); $decorated = $this->getMockBuilder(ClassMetadataFactoryInterface::class)->getMock(); $factory = new CacheClassMetadataFactory($decorated, new ArrayAdapter()); diff --git a/src/Symfony/Component/Serializer/Tests/Mapping/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/Serializer/Tests/Mapping/Loader/YamlFileLoaderTest.php index 73f5f4a4f1..cc00ae2d79 100644 --- a/src/Symfony/Component/Serializer/Tests/Mapping/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Mapping/Loader/YamlFileLoaderTest.php @@ -60,11 +60,9 @@ class YamlFileLoaderTest extends TestCase $this->assertFalse($loader->loadClassMetadata($this->metadata)); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\MappingException - */ public function testLoadClassMetadataReturnsThrowsInvalidMapping() { + $this->expectException('Symfony\Component\Serializer\Exception\MappingException'); $loader = new YamlFileLoader(__DIR__.'/../../Fixtures/invalid-mapping.yml'); $loader->loadClassMetadata($this->metadata); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php index f8d0f88cc1..677f0a6f6f 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php @@ -59,12 +59,10 @@ class AbstractObjectNormalizerTest extends TestCase $this->assertInstanceOf(__NAMESPACE__.'\Dummy', $normalizer->instantiateObject($data, $class, $context, new \ReflectionClass($class), [])); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\ExtraAttributesException - * @expectedExceptionMessage Extra attributes are not allowed ("fooFoo", "fooBar" are unknown). - */ public function testDenormalizeWithExtraAttributes() { + $this->expectException('Symfony\Component\Serializer\Exception\ExtraAttributesException'); + $this->expectExceptionMessage('Extra attributes are not allowed ("fooFoo", "fooBar" are unknown).'); $factory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $normalizer = new AbstractObjectNormalizerDummy($factory); $normalizer->denormalize( @@ -75,12 +73,10 @@ class AbstractObjectNormalizerTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\ExtraAttributesException - * @expectedExceptionMessage Extra attributes are not allowed ("fooFoo", "fooBar" are unknown). - */ public function testDenormalizeWithExtraAttributesAndNoGroupsWithMetadataFactory() { + $this->expectException('Symfony\Component\Serializer\Exception\ExtraAttributesException'); + $this->expectExceptionMessage('Extra attributes are not allowed ("fooFoo", "fooBar" are unknown).'); $normalizer = new AbstractObjectNormalizerWithMetadata(); $normalizer->denormalize( ['fooFoo' => 'foo', 'fooBar' => 'bar', 'bar' => 'bar'], @@ -194,12 +190,11 @@ class AbstractObjectNormalizerTest extends TestCase /** * Test that additional attributes throw an exception if no metadata factory is specified. - * - * @expectedException \Symfony\Component\Serializer\Exception\LogicException - * @expectedExceptionMessage A class metadata factory must be provided in the constructor when setting "allow_extra_attributes" to false. */ public function testExtraAttributesException() { + $this->expectException('Symfony\Component\Serializer\Exception\LogicException'); + $this->expectExceptionMessage('A class metadata factory must be provided in the constructor when setting "allow_extra_attributes" to false.'); $normalizer = new ObjectNormalizer(); $normalizer->denormalize([], \stdClass::class, 'xml', [ diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/DataUriNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/DataUriNormalizerTest.php index 62a55ac02c..82a4f2d74b 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/DataUriNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/DataUriNormalizerTest.php @@ -114,21 +114,19 @@ class DataUriNormalizerTest extends TestCase $this->assertSame(file_get_contents(self::TEST_GIF_DATA), $this->getContent($file->openFile())); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - * @expectedExceptionMessage The provided "data:" URI is not valid. - */ public function testGiveNotAccessToLocalFiles() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); + $this->expectExceptionMessage('The provided "data:" URI is not valid.'); $this->normalizer->denormalize('/etc/shadow', 'SplFileObject'); } /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException * @dataProvider invalidUriProvider */ public function testInvalidData($uri) { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $this->normalizer->denormalize($uri, 'SplFileObject'); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/DateIntervalNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/DateIntervalNormalizerTest.php index 75061fffb5..fb6f01fbb9 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/DateIntervalNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/DateIntervalNormalizerTest.php @@ -65,12 +65,10 @@ class DateIntervalNormalizerTest extends TestCase $this->assertEquals($output, $normalizer->normalize(new \DateInterval($input))); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - * @expectedExceptionMessage The object must be an instance of "\DateInterval". - */ public function testNormalizeInvalidObjectThrowsException() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The object must be an instance of "\DateInterval".'); $this->normalizer->normalize(new \stdClass()); } @@ -102,36 +100,28 @@ class DateIntervalNormalizerTest extends TestCase $this->assertDateIntervalEquals(new \DateInterval($output), $normalizer->denormalize($input, \DateInterval::class)); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - */ public function testDenormalizeExpectsString() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); $this->normalizer->denormalize(1234, \DateInterval::class); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - * @expectedExceptionMessage Expected a valid ISO 8601 interval string. - */ public function testDenormalizeNonISO8601IntervalStringThrowsException() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); + $this->expectExceptionMessage('Expected a valid ISO 8601 interval string.'); $this->normalizer->denormalize('10 years 2 months 3 days', \DateInterval::class, null); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testDenormalizeInvalidDataThrowsException() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $this->normalizer->denormalize('invalid interval', \DateInterval::class); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testDenormalizeFormatMismatchThrowsException() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $this->normalizer->denormalize('P00Y00M00DT00H00M00S', \DateInterval::class, null, [DateIntervalNormalizer::FORMAT_KEY => 'P%yY%mM%dD']); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php index 138c50ac05..e8cd3ceeda 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php @@ -158,12 +158,10 @@ class DateTimeNormalizerTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - * @expectedExceptionMessage The object must implement the "\DateTimeInterface". - */ public function testNormalizeInvalidObjectThrowsException() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The object must implement the "\DateTimeInterface".'); $this->normalizer->normalize(new \stdClass()); } @@ -239,37 +237,29 @@ class DateTimeNormalizerTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testDenormalizeInvalidDataThrowsException() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $this->normalizer->denormalize('invalid date', \DateTimeInterface::class); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - * @expectedExceptionMessage The data is either an empty string or null, you should pass a string that can be parsed with the passed format or a valid DateTime string. - */ public function testDenormalizeNullThrowsException() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); + $this->expectExceptionMessage('The data is either an empty string or null, you should pass a string that can be parsed with the passed format or a valid DateTime string.'); $this->normalizer->denormalize(null, \DateTimeInterface::class); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - * @expectedExceptionMessage The data is either an empty string or null, you should pass a string that can be parsed with the passed format or a valid DateTime string. - */ public function testDenormalizeEmptyStringThrowsException() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); + $this->expectExceptionMessage('The data is either an empty string or null, you should pass a string that can be parsed with the passed format or a valid DateTime string.'); $this->normalizer->denormalize('', \DateTimeInterface::class); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testDenormalizeFormatMismatchThrowsException() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $this->normalizer->denormalize('2016-01-01T00:00:00+00:00', \DateTimeInterface::class, null, [DateTimeNormalizer::FORMAT_KEY => 'Y-m-d|']); } } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeZoneNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeZoneNormalizerTest.php index c2a851ef78..91d144e844 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeZoneNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeZoneNormalizerTest.php @@ -42,11 +42,9 @@ class DateTimeZoneNormalizerTest extends TestCase $this->assertEquals('Asia/Tokyo', $this->normalizer->normalize(new \DateTimeZone('Asia/Tokyo'))); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - */ public function testNormalizeBadObjectTypeThrowsException() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); $this->normalizer->normalize(new \stdClass()); } @@ -63,19 +61,15 @@ class DateTimeZoneNormalizerTest extends TestCase $this->assertEquals(new \DateTimeZone('Asia/Tokyo'), $this->normalizer->denormalize('Asia/Tokyo', \DateTimeZone::class, null)); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\NotNormalizableValueException - */ public function testDenormalizeNullTimeZoneThrowsException() { + $this->expectException('Symfony\Component\Serializer\Exception\NotNormalizableValueException'); $this->normalizer->denormalize(null, \DateTimeZone::class, null); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\NotNormalizableValueException - */ public function testDenormalizeBadTimeZoneThrowsException() { + $this->expectException('Symfony\Component\Serializer\Exception\NotNormalizableValueException'); $this->normalizer->denormalize('Jupiter/Europa', \DateTimeZone::class, null); } } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php index f2adbb8c25..5fa964740e 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php @@ -364,12 +364,10 @@ class GetSetMethodNormalizerTest extends TestCase return $normalizer; } - /** - * @expectedException \Symfony\Component\Serializer\Exception\LogicException - * @expectedExceptionMessage Cannot normalize attribute "object" because the injected serializer is not a normalizer - */ public function testUnableToNormalizeObjectAttribute() { + $this->expectException('Symfony\Component\Serializer\Exception\LogicException'); + $this->expectExceptionMessage('Cannot normalize attribute "object" because the injected serializer is not a normalizer'); $serializer = $this->getMockBuilder('Symfony\Component\Serializer\SerializerInterface')->getMock(); $this->normalizer->setSerializer($serializer); diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php index f3d7f0d6e9..dfe5988e23 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php @@ -68,11 +68,9 @@ class JsonSerializableNormalizerTest extends TestCase $this->assertEquals('string_object', $this->normalizer->normalize(new JsonSerializableDummy())); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\CircularReferenceException - */ public function testCircularNormalize() { + $this->expectException('Symfony\Component\Serializer\Exception\CircularReferenceException'); $this->createNormalizer([JsonSerializableNormalizer::CIRCULAR_REFERENCE_LIMIT => 1]); $this->serializer @@ -88,12 +86,10 @@ class JsonSerializableNormalizerTest extends TestCase $this->assertEquals('string_object', $this->normalizer->normalize(new JsonSerializableDummy())); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - * @expectedExceptionMessage The object must implement "JsonSerializable". - */ public function testInvalidDataThrowException() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The object must implement "JsonSerializable".'); $this->normalizer->normalize(new \stdClass()); } } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php index 3ece2a0df5..3cc2e11d47 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php @@ -230,12 +230,10 @@ class ObjectNormalizerTest extends TestCase $this->assertNull($obj->getInner()); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\RuntimeException - * @expectedExceptionMessage Could not determine the class of the parameter "unknown". - */ public function testConstructorWithUnknownObjectTypeHintDenormalize() { + $this->expectException('Symfony\Component\Serializer\Exception\RuntimeException'); + $this->expectExceptionMessage('Could not determine the class of the parameter "unknown".'); $data = [ 'id' => 10, 'unknown' => [ @@ -490,12 +488,10 @@ class ObjectNormalizerTest extends TestCase return $normalizer; } - /** - * @expectedException \Symfony\Component\Serializer\Exception\LogicException - * @expectedExceptionMessage Cannot normalize attribute "object" because the injected serializer is not a normalizer - */ public function testUnableToNormalizeObjectAttribute() { + $this->expectException('Symfony\Component\Serializer\Exception\LogicException'); + $this->expectExceptionMessage('Cannot normalize attribute "object" because the injected serializer is not a normalizer'); $serializer = $this->getMockBuilder('Symfony\Component\Serializer\SerializerInterface')->getMock(); $this->normalizer->setSerializer($serializer); @@ -545,11 +541,9 @@ class ObjectNormalizerTest extends TestCase }])); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testThrowUnexpectedValueException() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $this->normalizer->denormalize(['foo' => 'bar'], ObjectTypeHinted::class); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php index dbe281f62b..0ed5e34c00 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php @@ -313,12 +313,10 @@ class PropertyNormalizerTest extends TestCase $this->assertEquals('out_of_scope', PropertyDummy::$outOfScope); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\LogicException - * @expectedExceptionMessage Cannot normalize attribute "bar" because the injected serializer is not a normalizer - */ public function testUnableToNormalizeObjectAttribute() { + $this->expectException('Symfony\Component\Serializer\Exception\LogicException'); + $this->expectExceptionMessage('Cannot normalize attribute "bar" because the injected serializer is not a normalizer'); $serializer = $this->getMockBuilder('Symfony\Component\Serializer\SerializerInterface')->getMock(); $this->normalizer->setSerializer($serializer); diff --git a/src/Symfony/Component/Serializer/Tests/SerializerTest.php b/src/Symfony/Component/Serializer/Tests/SerializerTest.php index bac467caf8..400668d0aa 100644 --- a/src/Symfony/Component/Serializer/Tests/SerializerTest.php +++ b/src/Symfony/Component/Serializer/Tests/SerializerTest.php @@ -13,6 +13,7 @@ namespace Symfony\Component\Serializer\Tests; use Doctrine\Common\Annotations\AnnotationReader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor; use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor; use Symfony\Component\Serializer\Encoder\JsonEncoder; @@ -46,6 +47,8 @@ use Symfony\Component\Serializer\Tests\Normalizer\TestNormalizer; class SerializerTest extends TestCase { + use ForwardCompatTestTrait; + public function testInterface() { $serializer = new Serializer(); @@ -57,29 +60,25 @@ class SerializerTest extends TestCase $this->assertInstanceOf('Symfony\Component\Serializer\Encoder\DecoderInterface', $serializer); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - * @expectedExceptionMessage The class "stdClass" neither implements "Symfony\Component\Serializer\Normalizer\NormalizerInterface" nor "Symfony\Component\Serializer\Normalizer\DenormalizerInterface". - */ public function testItThrowsExceptionOnInvalidNormalizer() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The class "stdClass" neither implements "Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface" nor "Symfony\\Component\\Serializer\\Normalizer\\DenormalizerInterface".'); + new Serializer([new \stdClass()]); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException - * @expectedExceptionMessage The class "stdClass" neither implements "Symfony\Component\Serializer\Encoder\EncoderInterface" nor "Symfony\Component\Serializer\Encoder\DecoderInterface" - */ public function testItThrowsExceptionOnInvalidEncoder() { + $this->expectException('Symfony\Component\Serializer\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The class "stdClass" neither implements "Symfony\\Component\\Serializer\\Encoder\\EncoderInterface" nor "Symfony\\Component\\Serializer\\Encoder\\DecoderInterface"'); + new Serializer([], [new \stdClass()]); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testNormalizeNoMatch() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $serializer = new Serializer([$this->getMockBuilder('Symfony\Component\Serializer\Normalizer\CustomNormalizer')->getMock()]); $serializer->normalize(new \stdClass(), 'xml'); } @@ -98,29 +97,23 @@ class SerializerTest extends TestCase $this->assertEquals('{"foo":"normalizedFoo","bar":"normalizedBar"}', $result); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testNormalizeOnDenormalizer() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $serializer = new Serializer([new TestDenormalizer()], []); $this->assertTrue($serializer->normalize(new \stdClass(), 'json')); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testDenormalizeNoMatch() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $serializer = new Serializer([$this->getMockBuilder('Symfony\Component\Serializer\Normalizer\CustomNormalizer')->getMock()]); $serializer->denormalize('foo', 'stdClass'); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testDenormalizeOnNormalizer() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $serializer = new Serializer([new TestNormalizer()], []); $data = ['title' => 'foo', 'numbers' => [5, 3]]; $this->assertTrue($serializer->denormalize(json_encode($data), 'stdClass', 'json')); @@ -202,21 +195,17 @@ class SerializerTest extends TestCase $this->assertEquals(json_encode($data), $result); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testSerializeNoEncoder() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $serializer = new Serializer([], []); $data = ['title' => 'foo', 'numbers' => [5, 3]]; $serializer->serialize($data, 'json'); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\LogicException - */ public function testSerializeNoNormalizer() { + $this->expectException('Symfony\Component\Serializer\Exception\LogicException'); $serializer = new Serializer([], ['json' => new JsonEncoder()]); $data = ['title' => 'foo', 'numbers' => [5, 3]]; $serializer->serialize(Model::fromArray($data), 'json'); @@ -240,31 +229,25 @@ class SerializerTest extends TestCase $this->assertEquals($data, $result->toArray()); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\LogicException - */ public function testDeserializeNoNormalizer() { + $this->expectException('Symfony\Component\Serializer\Exception\LogicException'); $serializer = new Serializer([], ['json' => new JsonEncoder()]); $data = ['title' => 'foo', 'numbers' => [5, 3]]; $serializer->deserialize(json_encode($data), '\Symfony\Component\Serializer\Tests\Model', 'json'); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testDeserializeWrongNormalizer() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $serializer = new Serializer([new CustomNormalizer()], ['json' => new JsonEncoder()]); $data = ['title' => 'foo', 'numbers' => [5, 3]]; $serializer->deserialize(json_encode($data), '\Symfony\Component\Serializer\Tests\Model', 'json'); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException - */ public function testDeserializeNoEncoder() { + $this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException'); $serializer = new Serializer([], []); $data = ['title' => 'foo', 'numbers' => [5, 3]]; $serializer->deserialize(json_encode($data), '\Symfony\Component\Serializer\Tests\Model', 'json'); @@ -469,21 +452,17 @@ class SerializerTest extends TestCase $this->assertEquals($example, $deserialized); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\RuntimeException - * @expectedExceptionMessage The type "second" has no mapped class for the abstract object "Symfony\Component\Serializer\Tests\Fixtures\DummyMessageInterface" - */ public function testExceptionWhenTypeIsNotKnownInDiscriminator() { + $this->expectException('Symfony\Component\Serializer\Exception\RuntimeException'); + $this->expectExceptionMessage('The type "second" has no mapped class for the abstract object "Symfony\Component\Serializer\Tests\Fixtures\DummyMessageInterface"'); $this->serializerWithClassDiscriminator()->deserialize('{"type":"second","one":1}', DummyMessageInterface::class, 'json'); } - /** - * @expectedException \Symfony\Component\Serializer\Exception\RuntimeException - * @expectedExceptionMessage Type property "type" not found for the abstract object "Symfony\Component\Serializer\Tests\Fixtures\DummyMessageInterface" - */ public function testExceptionWhenTypeIsNotInTheBodyToDeserialiaze() { + $this->expectException('Symfony\Component\Serializer\Exception\RuntimeException'); + $this->expectExceptionMessage('Type property "type" not found for the abstract object "Symfony\Component\Serializer\Tests\Fixtures\DummyMessageInterface"'); $this->serializerWithClassDiscriminator()->deserialize('{"one":1}', DummyMessageInterface::class, 'json'); } diff --git a/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php b/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php index 5d94e48fe8..dade44350f 100644 --- a/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php +++ b/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Stopwatch\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Stopwatch\StopwatchEvent; /** @@ -23,6 +24,8 @@ use Symfony\Component\Stopwatch\StopwatchEvent; */ class StopwatchEventTest extends TestCase { + use ForwardCompatTestTrait; + const DELTA = 37; public function testGetOrigin() @@ -103,11 +106,9 @@ class StopwatchEventTest extends TestCase $this->assertEquals(100, $event->getDuration(), '', self::DELTA); } - /** - * @expectedException \LogicException - */ public function testStopWithoutStart() { + $this->expectException('LogicException'); $event = new StopwatchEvent(microtime(true) * 1000); $event->stop(); } diff --git a/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php b/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php index d70e803e43..6a7ef1582c 100644 --- a/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php +++ b/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php @@ -93,20 +93,16 @@ class StopwatchTest extends TestCase $this->assertEquals(200, $event->getDuration(), '', self::DELTA); } - /** - * @expectedException \LogicException - */ public function testUnknownEvent() { + $this->expectException('LogicException'); $stopwatch = new Stopwatch(); $stopwatch->getEvent('foo'); } - /** - * @expectedException \LogicException - */ public function testStopWithoutStart() { + $this->expectException('LogicException'); $stopwatch = new Stopwatch(); $stopwatch->stop('foo'); } @@ -168,11 +164,9 @@ class StopwatchTest extends TestCase $this->assertCount(2, $events['__section__']->getPeriods()); } - /** - * @expectedException \LogicException - */ public function testReopenANewSectionShouldThrowAnException() { + $this->expectException('LogicException'); $stopwatch = new Stopwatch(); $stopwatch->openSection('section'); } diff --git a/src/Symfony/Component/Templating/Tests/DelegatingEngineTest.php b/src/Symfony/Component/Templating/Tests/DelegatingEngineTest.php index 3d61ec2716..07c3387d46 100644 --- a/src/Symfony/Component/Templating/Tests/DelegatingEngineTest.php +++ b/src/Symfony/Component/Templating/Tests/DelegatingEngineTest.php @@ -12,12 +12,15 @@ namespace Symfony\Component\Templating\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Templating\DelegatingEngine; use Symfony\Component\Templating\EngineInterface; use Symfony\Component\Templating\StreamingEngineInterface; class DelegatingEngineTest extends TestCase { + use ForwardCompatTestTrait; + public function testRenderDelegatesToSupportedEngine() { $firstEngine = $this->getEngineMock('template.php', false); @@ -34,12 +37,10 @@ class DelegatingEngineTest extends TestCase $this->assertSame('', $result); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage No engine is able to work with the template "template.php" - */ public function testRenderWithNoSupportedEngine() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('No engine is able to work with the template "template.php"'); $firstEngine = $this->getEngineMock('template.php', false); $secondEngine = $this->getEngineMock('template.php', false); @@ -61,12 +62,10 @@ class DelegatingEngineTest extends TestCase $this->assertNull($result); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Template "template.php" cannot be streamed as the engine supporting it does not implement StreamingEngineInterface - */ public function testStreamRequiresStreamingEngine() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Template "template.php" cannot be streamed as the engine supporting it does not implement StreamingEngineInterface'); $delegatingEngine = new DelegatingEngine([new TestEngine()]); $delegatingEngine->stream('template.php', ['foo' => 'bar']); } @@ -112,12 +111,10 @@ class DelegatingEngineTest extends TestCase $this->assertSame($secondEngine, $delegatingEngine->getEngine('template.php')); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage No engine is able to work with the template "template.php" - */ public function testGetInvalidEngine() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('No engine is able to work with the template "template.php"'); $firstEngine = $this->getEngineMock('template.php', false); $secondEngine = $this->getEngineMock('template.php', false); diff --git a/src/Symfony/Component/Templating/Tests/PhpEngineTest.php b/src/Symfony/Component/Templating/Tests/PhpEngineTest.php index cfa6c17516..244e8b8f79 100644 --- a/src/Symfony/Component/Templating/Tests/PhpEngineTest.php +++ b/src/Symfony/Component/Templating/Tests/PhpEngineTest.php @@ -127,11 +127,11 @@ class PhpEngineTest extends TestCase } /** - * @expectedException \InvalidArgumentException * @dataProvider forbiddenParameterNames */ public function testRenderForbiddenParameter($name) { + $this->expectException('InvalidArgumentException'); $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader); $this->loader->setTemplate('foo.php', 'bar'); $engine->render('foo.php', [$name => 'foo']); diff --git a/src/Symfony/Component/Translation/Tests/Command/XliffLintCommandTest.php b/src/Symfony/Component/Translation/Tests/Command/XliffLintCommandTest.php index abda2135fc..472c510365 100644 --- a/src/Symfony/Component/Translation/Tests/Command/XliffLintCommandTest.php +++ b/src/Symfony/Component/Translation/Tests/Command/XliffLintCommandTest.php @@ -105,11 +105,9 @@ class XliffLintCommandTest extends TestCase $this->assertContains('[OK] All 1 XLIFF files contain valid syntax.', trim($tester->getDisplay())); } - /** - * @expectedException \RuntimeException - */ public function testLintFileNotReadable() { + $this->expectException('RuntimeException'); $tester = $this->createCommandTester(); $filename = $this->createFile(); unlink($filename); diff --git a/src/Symfony/Component/Translation/Tests/DependencyInjection/TranslationExtractorPassTest.php b/src/Symfony/Component/Translation/Tests/DependencyInjection/TranslationExtractorPassTest.php index a638498b6b..b9996c8ed3 100644 --- a/src/Symfony/Component/Translation/Tests/DependencyInjection/TranslationExtractorPassTest.php +++ b/src/Symfony/Component/Translation/Tests/DependencyInjection/TranslationExtractorPassTest.php @@ -12,12 +12,15 @@ namespace Symfony\Component\Translation\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\Translation\DependencyInjection\TranslationExtractorPass; class TranslationExtractorPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testProcess() { $container = new ContainerBuilder(); @@ -46,12 +49,10 @@ class TranslationExtractorPassTest extends TestCase $this->assertCount($aliasesBefore, $container->getAliases()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The alias for the tag "translation.extractor" of service "foo.id" must be set. - */ public function testProcessMissingAlias() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The alias for the tag "translation.extractor" of service "foo.id" must be set.'); $definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->disableOriginalConstructor()->getMock(); $container = new ContainerBuilder(); $container->register('translation.extractor'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.php index 4fd5752db2..13b76bf35b 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Translation\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Translation\Loader\CsvFileLoader; class CsvFileLoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testLoad() { $loader = new CsvFileLoader(); @@ -39,21 +42,17 @@ class CsvFileLoaderTest extends TestCase $this->assertEquals([new FileResource($resource)], $catalogue->getResources()); } - /** - * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException - */ public function testLoadNonExistingResource() { + $this->expectException('Symfony\Component\Translation\Exception\NotFoundResourceException'); $loader = new CsvFileLoader(); $resource = __DIR__.'/../fixtures/not-exists.csv'; $loader->load($resource, 'en', 'domain1'); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - */ public function testLoadNonLocalResource() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); $loader = new CsvFileLoader(); $resource = 'http://example.com/resources.csv'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.php index 601680af8a..db845a8d82 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Translation\Tests\Loader; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Translation\Loader\IcuDatFileLoader; @@ -19,11 +20,11 @@ use Symfony\Component\Translation\Loader\IcuDatFileLoader; */ class IcuDatFileLoaderTest extends LocalizedTestCase { - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - */ + use ForwardCompatTestTrait; + public function testLoadInvalidResource() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); $loader = new IcuDatFileLoader(); $loader->load(__DIR__.'/../fixtures/resourcebundle/corrupted/resources', 'es', 'domain2'); } @@ -53,11 +54,9 @@ class IcuDatFileLoaderTest extends LocalizedTestCase $this->assertEquals([new FileResource($resource.'.dat')], $catalogue->getResources()); } - /** - * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException - */ public function testLoadNonExistingResource() { + $this->expectException('Symfony\Component\Translation\Exception\NotFoundResourceException'); $loader = new IcuDatFileLoader(); $loader->load(__DIR__.'/../fixtures/non-existing.txt', 'en', 'domain1'); } diff --git a/src/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.php index 962c3af2ef..25d5082747 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Translation\Tests\Loader; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Resource\DirectoryResource; use Symfony\Component\Translation\Loader\IcuResFileLoader; @@ -19,6 +20,8 @@ use Symfony\Component\Translation\Loader\IcuResFileLoader; */ class IcuResFileLoaderTest extends LocalizedTestCase { + use ForwardCompatTestTrait; + public function testLoad() { // resource is build using genrb command @@ -31,20 +34,16 @@ class IcuResFileLoaderTest extends LocalizedTestCase $this->assertEquals([new DirectoryResource($resource)], $catalogue->getResources()); } - /** - * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException - */ public function testLoadNonExistingResource() { + $this->expectException('Symfony\Component\Translation\Exception\NotFoundResourceException'); $loader = new IcuResFileLoader(); $loader->load(__DIR__.'/../fixtures/non-existing.txt', 'en', 'domain1'); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - */ public function testLoadInvalidResource() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); $loader = new IcuResFileLoader(); $loader->load(__DIR__.'/../fixtures/resourcebundle/corrupted', 'en', 'domain1'); } diff --git a/src/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.php index e0d8b2f4c4..47ffc9b967 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Translation\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Translation\Loader\IniFileLoader; class IniFileLoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testLoad() { $loader = new IniFileLoader(); @@ -39,11 +42,9 @@ class IniFileLoaderTest extends TestCase $this->assertEquals([new FileResource($resource)], $catalogue->getResources()); } - /** - * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException - */ public function testLoadNonExistingResource() { + $this->expectException('Symfony\Component\Translation\Exception\NotFoundResourceException'); $loader = new IniFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.ini'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.php index 4c507da5ab..0d452e16df 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Translation\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Translation\Loader\JsonFileLoader; class JsonFileLoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testLoad() { $loader = new JsonFileLoader(); @@ -39,22 +42,18 @@ class JsonFileLoaderTest extends TestCase $this->assertEquals([new FileResource($resource)], $catalogue->getResources()); } - /** - * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException - */ public function testLoadNonExistingResource() { + $this->expectException('Symfony\Component\Translation\Exception\NotFoundResourceException'); $loader = new JsonFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.json'; $loader->load($resource, 'en', 'domain1'); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - * @expectedExceptionMessage Error parsing JSON - Syntax error, malformed JSON - */ public function testParseException() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); + $this->expectExceptionMessage('Error parsing JSON - Syntax error, malformed JSON'); $loader = new JsonFileLoader(); $resource = __DIR__.'/../fixtures/malformed.json'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.php index d6adecb173..f89584259f 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Translation\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Translation\Loader\MoFileLoader; class MoFileLoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testLoad() { $loader = new MoFileLoader(); @@ -42,21 +45,17 @@ class MoFileLoaderTest extends TestCase $this->assertEquals([new FileResource($resource)], $catalogue->getResources()); } - /** - * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException - */ public function testLoadNonExistingResource() { + $this->expectException('Symfony\Component\Translation\Exception\NotFoundResourceException'); $loader = new MoFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.mo'; $loader->load($resource, 'en', 'domain1'); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - */ public function testLoadInvalidResource() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); $loader = new MoFileLoader(); $resource = __DIR__.'/../fixtures/empty.mo'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.php index 68cb2d0b72..d6e9712200 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Translation\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Translation\Loader\PhpFileLoader; class PhpFileLoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testLoad() { $loader = new PhpFileLoader(); @@ -28,21 +31,17 @@ class PhpFileLoaderTest extends TestCase $this->assertEquals([new FileResource($resource)], $catalogue->getResources()); } - /** - * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException - */ public function testLoadNonExistingResource() { + $this->expectException('Symfony\Component\Translation\Exception\NotFoundResourceException'); $loader = new PhpFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.php'; $loader->load($resource, 'en', 'domain1'); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - */ public function testLoadThrowsAnExceptionIfFileNotLocal() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); $loader = new PhpFileLoader(); $resource = 'http://example.com/resources.php'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.php index cb94e90a94..e55d6db899 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Translation\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Translation\Loader\PoFileLoader; class PoFileLoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testLoad() { $loader = new PoFileLoader(); @@ -53,11 +56,9 @@ class PoFileLoaderTest extends TestCase $this->assertEquals([new FileResource($resource)], $catalogue->getResources()); } - /** - * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException - */ public function testLoadNonExistingResource() { + $this->expectException('Symfony\Component\Translation\Exception\NotFoundResourceException'); $loader = new PoFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.po'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.php index e80d7c4b4e..6978c59ec5 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.php @@ -35,31 +35,25 @@ class QtFileLoaderTest extends TestCase $this->assertEquals([new FileResource($resource)], $catalogue->getResources()); } - /** - * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException - */ public function testLoadNonExistingResource() { + $this->expectException('Symfony\Component\Translation\Exception\NotFoundResourceException'); $loader = new QtFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.ts'; $loader->load($resource, 'en', 'domain1'); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - */ public function testLoadNonLocalResource() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); $loader = new QtFileLoader(); $resource = 'http://domain1.com/resources.ts'; $loader->load($resource, 'en', 'domain1'); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - */ public function testLoadInvalidResource() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); $loader = new QtFileLoader(); $resource = __DIR__.'/../fixtures/invalid-xml-resources.xlf'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php index 700a7a33e7..1db28d773b 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php @@ -109,50 +109,40 @@ class XliffFileLoaderTest extends TestCase $this->assertEquals('translated', $metadata['target-attributes']['state']); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - */ public function testLoadInvalidResource() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); $loader = new XliffFileLoader(); $loader->load(__DIR__.'/../fixtures/resources.php', 'en', 'domain1'); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - */ public function testLoadResourceDoesNotValidate() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); $loader = new XliffFileLoader(); $loader->load(__DIR__.'/../fixtures/non-valid.xlf', 'en', 'domain1'); } - /** - * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException - */ public function testLoadNonExistingResource() { + $this->expectException('Symfony\Component\Translation\Exception\NotFoundResourceException'); $loader = new XliffFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.xlf'; $loader->load($resource, 'en', 'domain1'); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - */ public function testLoadThrowsAnExceptionIfFileNotLocal() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); $loader = new XliffFileLoader(); $resource = 'http://example.com/resources.xlf'; $loader->load($resource, 'en', 'domain1'); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - * @expectedExceptionMessage Document types are not allowed. - */ public function testDocTypeIsNotAllowed() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); + $this->expectExceptionMessage('Document types are not allowed.'); $loader = new XliffFileLoader(); $loader->load(__DIR__.'/../fixtures/withdoctype.xlf', 'en', 'domain1'); } diff --git a/src/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.php index a535db56fc..d05d65d030 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Translation\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Translation\Loader\YamlFileLoader; class YamlFileLoaderTest extends TestCase { + use ForwardCompatTestTrait; + public function testLoad() { $loader = new YamlFileLoader(); @@ -39,31 +42,25 @@ class YamlFileLoaderTest extends TestCase $this->assertEquals([new FileResource($resource)], $catalogue->getResources()); } - /** - * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException - */ public function testLoadNonExistingResource() { + $this->expectException('Symfony\Component\Translation\Exception\NotFoundResourceException'); $loader = new YamlFileLoader(); $resource = __DIR__.'/../fixtures/non-existing.yml'; $loader->load($resource, 'en', 'domain1'); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - */ public function testLoadThrowsAnExceptionIfFileNotLocal() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); $loader = new YamlFileLoader(); $resource = 'http://example.com/resources.yml'; $loader->load($resource, 'en', 'domain1'); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException - */ public function testLoadThrowsAnExceptionIfNotAnArray() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidResourceException'); $loader = new YamlFileLoader(); $resource = __DIR__.'/../fixtures/non-valid.yml'; $loader->load($resource, 'en', 'domain1'); diff --git a/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php b/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php index cf0dd1a24c..fb87d02573 100644 --- a/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php +++ b/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Translation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Translation\MessageCatalogue; class MessageCatalogueTest extends TestCase { + use ForwardCompatTestTrait; + public function testGetLocale() { $catalogue = new MessageCatalogue('en'); @@ -153,11 +156,9 @@ class MessageCatalogueTest extends TestCase $this->assertEquals([$r, $r1, $r2], $catalogue->getResources()); } - /** - * @expectedException \Symfony\Component\Translation\Exception\LogicException - */ public function testAddFallbackCatalogueWithParentCircularReference() { + $this->expectException('Symfony\Component\Translation\Exception\LogicException'); $main = new MessageCatalogue('en_US'); $fallback = new MessageCatalogue('fr_FR'); @@ -165,11 +166,9 @@ class MessageCatalogueTest extends TestCase $main->addFallbackCatalogue($fallback); } - /** - * @expectedException \Symfony\Component\Translation\Exception\LogicException - */ public function testAddFallbackCatalogueWithFallbackCircularReference() { + $this->expectException('Symfony\Component\Translation\Exception\LogicException'); $fr = new MessageCatalogue('fr'); $en = new MessageCatalogue('en'); $es = new MessageCatalogue('es'); @@ -179,11 +178,9 @@ class MessageCatalogueTest extends TestCase $en->addFallbackCatalogue($fr); } - /** - * @expectedException \Symfony\Component\Translation\Exception\LogicException - */ public function testAddCatalogueWhenLocaleIsNotTheSameAsTheCurrentOne() { + $this->expectException('Symfony\Component\Translation\Exception\LogicException'); $catalogue = new MessageCatalogue('en'); $catalogue->addCatalogue(new MessageCatalogue('fr', [])); } diff --git a/src/Symfony/Component/Translation/Tests/TranslatorTest.php b/src/Symfony/Component/Translation/Tests/TranslatorTest.php index 7076f58213..efd8ac18c0 100644 --- a/src/Symfony/Component/Translation/Tests/TranslatorTest.php +++ b/src/Symfony/Component/Translation/Tests/TranslatorTest.php @@ -12,18 +12,21 @@ namespace Symfony\Component\Translation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Translation\Loader\ArrayLoader; use Symfony\Component\Translation\MessageCatalogue; use Symfony\Component\Translation\Translator; class TranslatorTest extends TestCase { + use ForwardCompatTestTrait; + /** - * @dataProvider getInvalidLocalesTests - * @expectedException \Symfony\Component\Translation\Exception\InvalidArgumentException + * @dataProvider getInvalidLocalesTests */ public function testConstructorInvalidLocale($locale) { + $this->expectException('Symfony\Component\Translation\Exception\InvalidArgumentException'); new Translator($locale); } @@ -55,11 +58,11 @@ class TranslatorTest extends TestCase } /** - * @dataProvider getInvalidLocalesTests - * @expectedException \Symfony\Component\Translation\Exception\InvalidArgumentException + * @dataProvider getInvalidLocalesTests */ public function testSetInvalidLocale($locale) { + $this->expectException('Symfony\Component\Translation\Exception\InvalidArgumentException'); $translator = new Translator('fr'); $translator->setLocale($locale); } @@ -138,11 +141,11 @@ class TranslatorTest extends TestCase } /** - * @dataProvider getInvalidLocalesTests - * @expectedException \Symfony\Component\Translation\Exception\InvalidArgumentException + * @dataProvider getInvalidLocalesTests */ public function testSetFallbackInvalidLocales($locale) { + $this->expectException('Symfony\Component\Translation\Exception\InvalidArgumentException'); $translator = new Translator('fr'); $translator->setFallbackLocales(['fr', $locale]); } @@ -170,11 +173,11 @@ class TranslatorTest extends TestCase } /** - * @dataProvider getInvalidLocalesTests - * @expectedException \Symfony\Component\Translation\Exception\InvalidArgumentException + * @dataProvider getInvalidLocalesTests */ public function testAddResourceInvalidLocales($locale) { + $this->expectException('Symfony\Component\Translation\Exception\InvalidArgumentException'); $translator = new Translator('fr'); $translator->addResource('array', ['foo' => 'foofoo'], $locale); } @@ -208,11 +211,11 @@ class TranslatorTest extends TestCase } /** - * @dataProvider getTransFileTests - * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException + * @dataProvider getTransFileTests */ public function testTransWithoutFallbackLocaleFile($format, $loader) { + $this->expectException('Symfony\Component\Translation\Exception\NotFoundResourceException'); $loaderClass = 'Symfony\\Component\\Translation\\Loader\\'.$loader; $translator = new Translator('en'); $translator->addLoader($format, new $loaderClass()); @@ -303,11 +306,9 @@ class TranslatorTest extends TestCase $this->assertEquals('non-existent', $translator->trans('non-existent')); } - /** - * @expectedException \Symfony\Component\Translation\Exception\RuntimeException - */ public function testWhenAResourceHasNoRegisteredLoader() { + $this->expectException('Symfony\Component\Translation\Exception\RuntimeException'); $translator = new Translator('en'); $translator->addResource('array', ['foo' => 'foofoo'], 'en'); @@ -357,11 +358,11 @@ class TranslatorTest extends TestCase } /** - * @dataProvider getInvalidLocalesTests - * @expectedException \Symfony\Component\Translation\Exception\InvalidArgumentException + * @dataProvider getInvalidLocalesTests */ public function testTransInvalidLocale($locale) { + $this->expectException('Symfony\Component\Translation\Exception\InvalidArgumentException'); $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); $translator->addResource('array', ['foo' => 'foofoo'], 'en'); diff --git a/src/Symfony/Component/Validator/Tests/ConstraintTest.php b/src/Symfony/Component/Validator/Tests/ConstraintTest.php index cc36eaac8c..9ebcd4e84c 100644 --- a/src/Symfony/Component/Validator/Tests/ConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/ConstraintTest.php @@ -207,11 +207,9 @@ class ConstraintTest extends TestCase $this->assertSame(['MyGroup'], $constraint->groups); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - */ public function testGetErrorNameForUnknownCode() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); Constraint::getErrorName(1); } @@ -226,12 +224,10 @@ class ConstraintTest extends TestCase $this->assertEquals($options, $constraint->property2); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidOptionsException - * @expectedExceptionMessage The options "0", "5" do not exist in constraint "Symfony\Component\Validator\Tests\Fixtures\ConstraintA". - */ public function testInvalidOptions() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidOptionsException'); + $this->expectExceptionMessage('The options "0", "5" do not exist in constraint "Symfony\Component\Validator\Tests\Fixtures\ConstraintA".'); new ConstraintA(['property2' => 'foo', 'bar', 5 => 'baz']); } @@ -246,12 +242,10 @@ class ConstraintTest extends TestCase $this->assertEquals('foo', $constraint->property1); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage No default option is configured for constraint "Symfony\Component\Validator\Tests\Fixtures\ConstraintB". - */ public function testAnnotationSetUndefinedDefaultOption() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('No default option is configured for constraint "Symfony\Component\Validator\Tests\Fixtures\ConstraintB".'); new ConstraintB(['value' => 1]); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php b/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php index c70a2309a7..f4d3e5d3d0 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php @@ -84,20 +84,18 @@ abstract class AbstractComparisonValidatorTestCase extends ConstraintValidatorTe /** * @dataProvider provideInvalidConstraintOptions - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage requires either the "value" or "propertyPath" option to be set. */ public function testThrowsConstraintExceptionIfNoValueOrPropertyPath($options) { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('requires either the "value" or "propertyPath" option to be set.'); $this->createConstraint($options); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage requires only one of the "value" or "propertyPath" options to be set, not both. - */ public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('requires only one of the "value" or "propertyPath" options to be set, not both.'); $this->createConstraint(([ 'value' => 'value', 'propertyPath' => 'propertyPath', diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AllTest.php b/src/Symfony/Component/Validator/Tests/Constraints/AllTest.php index cdd72a22eb..450248a6b3 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/AllTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/AllTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\All; use Symfony\Component\Validator\Constraints\Valid; @@ -20,21 +21,19 @@ use Symfony\Component\Validator\Constraints\Valid; */ class AllTest extends TestCase { - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ + use ForwardCompatTestTrait; + public function testRejectNonConstraints() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new All([ 'foo', ]); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testRejectValidConstraint() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new All([ new Valid(), ]); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php index a0c64b5082..db7032fe14 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\All; use Symfony\Component\Validator\Constraints\AllValidator; use Symfony\Component\Validator\Constraints\NotNull; @@ -19,6 +20,8 @@ use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class AllValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new AllValidator(); @@ -31,11 +34,9 @@ class AllValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testThrowsExceptionIfNotTraversable() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate('foo.barbar', new All(new Range(['min' => 4]))); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php index b13fd874ff..80c00423e7 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php @@ -103,12 +103,10 @@ class BicValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage The "iban" and "ibanPropertyPath" options of the Iban constraint cannot be used at the same time - */ public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('The "iban" and "ibanPropertyPath" options of the Iban constraint cannot be used at the same time'); new Bic([ 'iban' => 'value', 'ibanPropertyPath' => 'propertyPath', @@ -129,11 +127,9 @@ class BicValidatorTest extends ConstraintValidatorTestCase $this->validator->validate('UNCRIT2B912', $constraint); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Bic()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php index 1c771c2c13..61b72e03aa 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\Callback; use Symfony\Component\Validator\Constraints\CallbackValidator; @@ -46,6 +47,8 @@ class CallbackValidatorTest_Object class CallbackValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new CallbackValidator(); @@ -180,21 +183,17 @@ class CallbackValidatorTest extends ConstraintValidatorTestCase ->assertRaised(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testExpectValidMethods() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $object = new CallbackValidatorTest_Object(); $this->validator->validate($object, new Callback(['callback' => ['foobar']])); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testExpectValidCallbacks() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $object = new CallbackValidatorTest_Object(); $this->validator->validate($object, new Callback(['callback' => ['foo', 'bar']])); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php index e55d19aa82..218d403af8 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Choice; use Symfony\Component\Validator\Constraints\ChoiceValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; @@ -22,6 +23,8 @@ function choice_callback() class ChoiceValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new ChoiceValidator(); @@ -37,11 +40,9 @@ class ChoiceValidatorTest extends ConstraintValidatorTestCase return ['foo', 'bar']; } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectArrayIfMultipleIsTrue() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $constraint = new Choice([ 'choices' => ['foo', 'bar'], 'multiple' => true, @@ -62,19 +63,15 @@ class ChoiceValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testChoicesOrCallbackExpected() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $this->validator->validate('foobar', new Choice()); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testValidCallbackExpected() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $this->validator->validate('foobar', new Choice(['callback' => 'abcd'])); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php index fec935082a..477e8b3844 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Collection; use Symfony\Component\Validator\Constraints\Email; use Symfony\Component\Validator\Constraints\Optional; @@ -23,51 +24,43 @@ use Symfony\Component\Validator\Constraints\Valid; */ class CollectionTest extends TestCase { - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ + use ForwardCompatTestTrait; + public function testRejectInvalidFieldsOption() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new Collection([ 'fields' => 'foo', ]); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testRejectNonConstraints() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new Collection([ 'foo' => 'bar', ]); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testRejectValidConstraint() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new Collection([ 'foo' => new Valid(), ]); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testRejectValidConstraintWithinOptional() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new Collection([ 'foo' => new Optional(new Valid()), ]); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testRejectValidConstraintWithinRequired() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new Collection([ 'foo' => new Required(new Valid()), ]); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php index 747be2499a..bf80c9bdd4 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Collection; use Symfony\Component\Validator\Constraints\CollectionValidator; use Symfony\Component\Validator\Constraints\NotNull; @@ -21,6 +22,8 @@ use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; abstract class CollectionValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new CollectionValidator(); @@ -52,11 +55,9 @@ abstract class CollectionValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testThrowsExceptionIfNotTraversable() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate('foobar', new Collection(['fields' => [ 'foo' => new Range(['min' => 4]), ]])); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CompositeTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CompositeTest.php index 3070e6a22f..4e6c891700 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CompositeTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CompositeTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Composite; use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\NotNull; @@ -37,6 +38,8 @@ class ConcreteComposite extends Composite */ class CompositeTest extends TestCase { + use ForwardCompatTestTrait; + public function testMergeNestedGroupsIfNoExplicitParentGroup() { $constraint = new ConcreteComposite([ @@ -79,11 +82,9 @@ class CompositeTest extends TestCase $this->assertEquals(['Strict'], $constraint->constraints[1]->groups); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testFailIfExplicitNestedGroupsNotSubsetOfExplicitParentGroups() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new ConcreteComposite([ 'constraints' => [ new NotNull(['groups' => ['Default', 'Foobar']]), @@ -114,33 +115,27 @@ class CompositeTest extends TestCase $this->assertEquals([$nestedConstraint], $constraint->constraints); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testFailIfNoConstraint() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new ConcreteComposite([ new NotNull(['groups' => 'Default']), 'NotBlank', ]); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testFailIfNoConstraintObject() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new ConcreteComposite([ new NotNull(['groups' => 'Default']), new \ArrayObject(), ]); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testValidCantBeNested() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new ConcreteComposite([ new Valid(), ]); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php index 7f019c78fb..e2a624e859 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Count; use Symfony\Component\Validator\Constraints\CountValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; @@ -20,6 +21,8 @@ use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; */ abstract class CountValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new CountValidator(); @@ -34,11 +37,9 @@ abstract class CountValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsCountableType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Count(5)); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php index 51352183e3..48edf6db3d 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Intl\Util\IntlTestHelper; use Symfony\Component\Validator\Constraints\Country; use Symfony\Component\Validator\Constraints\CountryValidator; @@ -18,6 +19,8 @@ use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class CountryValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new CountryValidator(); @@ -37,11 +40,9 @@ class CountryValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Country()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php index 0e41a97561..0bb6fe2e28 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Intl\Util\IntlTestHelper; use Symfony\Component\Validator\Constraints\Currency; use Symfony\Component\Validator\Constraints\CurrencyValidator; @@ -18,6 +19,8 @@ use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class CurrencyValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new CurrencyValidator(); @@ -37,11 +40,9 @@ class CurrencyValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Currency()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php index 968ce10178..5d22b6b163 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php @@ -11,12 +11,15 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\DateTime; use Symfony\Component\Validator\Constraints\DateTimeValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class DateTimeValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new DateTimeValidator(); @@ -36,11 +39,9 @@ class DateTimeValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new DateTime()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php index fa3bdd49ee..e3891152e4 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php @@ -11,12 +11,15 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Date; use Symfony\Component\Validator\Constraints\DateValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class DateValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new DateValidator(); @@ -36,11 +39,9 @@ class DateValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Date()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/EmailTest.php b/src/Symfony/Component/Validator/Tests/Constraints/EmailTest.php index 1472aaba12..57c71780df 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/EmailTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/EmailTest.php @@ -23,12 +23,10 @@ class EmailTest extends TestCase $this->assertEquals(Email::VALIDATION_MODE_STRICT, $subject->mode); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "mode" parameter value is not valid. - */ public function testUnknownModesTriggerException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "mode" parameter value is not valid.'); new Email(['mode' => 'Unknown Mode']); } @@ -39,21 +37,17 @@ class EmailTest extends TestCase $this->assertEquals('trim', $email->normalizer); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("string" given). - */ public function testInvalidNormalizerThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new Email(['normalizer' => 'Unknown Callable']); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("stdClass" given). - */ public function testInvalidNormalizerObjectThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new Email(['normalizer' => new \stdClass()]); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php index 2f3b1728d3..a84f8c00bc 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php @@ -25,12 +25,10 @@ class EmailValidatorTest extends ConstraintValidatorTestCase return new EmailValidator(Email::VALIDATION_MODE_LOOSE); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "defaultMode" parameter value is not valid. - */ public function testUnknownDefaultModeTriggerException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "defaultMode" parameter value is not valid.'); new EmailValidator('Unknown Mode'); } @@ -48,11 +46,9 @@ class EmailValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Email()); } @@ -219,12 +215,10 @@ class EmailValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The Symfony\Component\Validator\Constraints\Email::$mode parameter value is not valid. - */ public function testUnknownModesOnValidateTriggerException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The Symfony\Component\Validator\Constraints\Email::$mode parameter value is not valid.'); $constraint = new Email(); $constraint->mode = 'Unknown Mode'; diff --git a/src/Symfony/Component/Validator/Tests/Constraints/FileTest.php b/src/Symfony/Component/Validator/Tests/Constraints/FileTest.php index e0b6ec8f41..39e375b5e5 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/FileTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/FileTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\Validator\Tests\Constraints; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\File; use Symfony\Component\Validator\Exception\ConstraintDefinitionException; class FileTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider provideValidSizes */ @@ -52,10 +55,10 @@ class FileTest extends TestCase /** * @dataProvider provideInvalidSizes - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException */ public function testInvalidValueForMaxSizeThrowsExceptionAfterInitialization($maxSize) { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $file = new File(['maxSize' => 1000]); $file->maxSize = $maxSize; } @@ -77,10 +80,10 @@ class FileTest extends TestCase /** * @dataProvider provideInValidSizes - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException */ public function testInvalidMaxSize($maxSize) { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new File(['maxSize' => $maxSize]); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php index cdcbe4e24b..336cf3893c 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php @@ -69,11 +69,9 @@ abstract class FileValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleTypeOrFile() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new File()); } @@ -227,11 +225,9 @@ abstract class FileValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testInvalidMaxSize() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $constraint = new File([ 'maxSize' => '1abc', ]); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorWithPositiveOrZeroConstraintTest.php b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorWithPositiveOrZeroConstraintTest.php index 6a81129ef9..8b7a2f45af 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorWithPositiveOrZeroConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorWithPositiveOrZeroConstraintTest.php @@ -51,40 +51,34 @@ class GreaterThanOrEqualValidatorWithPositiveOrZeroConstraintTest extends Greate ]; } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage The "propertyPath" option of the "Symfony\Component\Validator\Constraints\PositiveOrZero" constraint cannot be set. - */ public function testThrowsConstraintExceptionIfPropertyPath() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('The "propertyPath" option of the "Symfony\Component\Validator\Constraints\PositiveOrZero" constraint cannot be set.'); return new PositiveOrZero(['propertyPath' => 'field']); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage The "value" option of the "Symfony\Component\Validator\Constraints\PositiveOrZero" constraint cannot be set. - */ public function testThrowsConstraintExceptionIfValue() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('The "value" option of the "Symfony\Component\Validator\Constraints\PositiveOrZero" constraint cannot be set.'); return new PositiveOrZero(['value' => 0]); } /** * @dataProvider provideInvalidConstraintOptions - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage requires either the "value" or "propertyPath" option to be set. */ public function testThrowsConstraintExceptionIfNoValueOrPropertyPath($options) { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('requires either the "value" or "propertyPath" option to be set.'); $this->markTestSkipped('Value option always set for PositiveOrZero constraint'); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage requires only one of the "value" or "propertyPath" options to be set, not both. - */ public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('requires only one of the "value" or "propertyPath" options to be set, not both.'); $this->markTestSkipped('Value option is set for PositiveOrZero constraint automatically'); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorWithPositiveConstraintTest.php b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorWithPositiveConstraintTest.php index ca75286dc7..7aa647df45 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorWithPositiveConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorWithPositiveConstraintTest.php @@ -49,40 +49,34 @@ class GreaterThanValidatorWithPositiveConstraintTest extends GreaterThanValidato ]; } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage The "propertyPath" option of the "Symfony\Component\Validator\Constraints\Positive" constraint cannot be set. - */ public function testThrowsConstraintExceptionIfPropertyPath() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('The "propertyPath" option of the "Symfony\Component\Validator\Constraints\Positive" constraint cannot be set.'); return new Positive(['propertyPath' => 'field']); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage The "value" option of the "Symfony\Component\Validator\Constraints\Positive" constraint cannot be set. - */ public function testThrowsConstraintExceptionIfValue() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('The "value" option of the "Symfony\Component\Validator\Constraints\Positive" constraint cannot be set.'); return new Positive(['value' => 0]); } /** * @dataProvider provideInvalidConstraintOptions - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage requires either the "value" or "propertyPath" option to be set. */ public function testThrowsConstraintExceptionIfNoValueOrPropertyPath($options) { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('requires either the "value" or "propertyPath" option to be set.'); $this->markTestSkipped('Value option always set for Positive constraint.'); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage requires only one of the "value" or "propertyPath" options to be set, not both. - */ public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('requires only one of the "value" or "propertyPath" options to be set, not both.'); $this->markTestSkipped('Value option is set for Positive constraint automatically'); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php index 22bb93bd09..461ef5e628 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php @@ -203,11 +203,9 @@ class ImageValidatorTest extends ConstraintValidatorTestCase ->assertRaised(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testInvalidMinWidth() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $constraint = new Image([ 'minWidth' => '1abc', ]); @@ -215,11 +213,9 @@ class ImageValidatorTest extends ConstraintValidatorTestCase $this->validator->validate($this->image, $constraint); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testInvalidMaxWidth() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $constraint = new Image([ 'maxWidth' => '1abc', ]); @@ -227,11 +223,9 @@ class ImageValidatorTest extends ConstraintValidatorTestCase $this->validator->validate($this->image, $constraint); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testInvalidMinHeight() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $constraint = new Image([ 'minHeight' => '1abc', ]); @@ -239,11 +233,9 @@ class ImageValidatorTest extends ConstraintValidatorTestCase $this->validator->validate($this->image, $constraint); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testInvalidMaxHeight() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $constraint = new Image([ 'maxHeight' => '1abc', ]); @@ -251,11 +243,9 @@ class ImageValidatorTest extends ConstraintValidatorTestCase $this->validator->validate($this->image, $constraint); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testInvalidMinPixels() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $constraint = new Image([ 'minPixels' => '1abc', ]); @@ -263,11 +253,9 @@ class ImageValidatorTest extends ConstraintValidatorTestCase $this->validator->validate($this->image, $constraint); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testInvalidMaxPixels() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $constraint = new Image([ 'maxPixels' => '1abc', ]); @@ -318,11 +306,9 @@ class ImageValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testInvalidMinRatio() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $constraint = new Image([ 'minRatio' => '1abc', ]); @@ -330,11 +316,9 @@ class ImageValidatorTest extends ConstraintValidatorTestCase $this->validator->validate($this->image, $constraint); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testInvalidMaxRatio() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $constraint = new Image([ 'maxRatio' => '1abc', ]); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IpTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IpTest.php index 9aa851604b..f8147ac27f 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IpTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IpTest.php @@ -26,21 +26,17 @@ class IpTest extends TestCase $this->assertEquals('trim', $ip->normalizer); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("string" given). - */ public function testInvalidNormalizerThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new Ip(['normalizer' => 'Unknown Callable']); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("stdClass" given). - */ public function testInvalidNormalizerObjectThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new Ip(['normalizer' => new \stdClass()]); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php index e589053083..8644888ed3 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php @@ -11,12 +11,15 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Ip; use Symfony\Component\Validator\Constraints\IpValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class IpValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new IpValidator(); @@ -36,19 +39,15 @@ class IpValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Ip()); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testInvalidValidatorVersion() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new Ip([ 'version' => 666, ]); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php index 74aaf91272..2cd38e9afe 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Isbn; use Symfony\Component\Validator\Constraints\IsbnValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; @@ -20,6 +21,8 @@ use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; */ class IsbnValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new IsbnValidator(); @@ -136,11 +139,9 @@ class IsbnValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $constraint = new Isbn(true); $this->validator->validate(new \stdClass(), $constraint); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php index ac82d69ba6..f26380d411 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Issn; use Symfony\Component\Validator\Constraints\IssnValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; @@ -20,6 +21,8 @@ use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; */ class IssnValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new IssnValidator(); @@ -106,11 +109,9 @@ class IssnValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $constraint = new Issn(); $this->validator->validate(new \stdClass(), $constraint); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php index 7d61dd4702..09c155b1e4 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Intl\Util\IntlTestHelper; use Symfony\Component\Validator\Constraints\Language; use Symfony\Component\Validator\Constraints\LanguageValidator; @@ -18,6 +19,8 @@ use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class LanguageValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new LanguageValidator(); @@ -37,11 +40,9 @@ class LanguageValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Language()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LengthTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LengthTest.php index 6a20ff541f..b0caef17c9 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LengthTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LengthTest.php @@ -26,21 +26,17 @@ class LengthTest extends TestCase $this->assertEquals('trim', $length->normalizer); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("string" given). - */ public function testInvalidNormalizerThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new Length(['min' => 0, 'max' => 10, 'normalizer' => 'Unknown Callable']); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("stdClass" given). - */ public function testInvalidNormalizerObjectThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new Length(['min' => 0, 'max' => 10, 'normalizer' => new \stdClass()]); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php index 240552c428..04571cb5fb 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php @@ -11,12 +11,15 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Length; use Symfony\Component\Validator\Constraints\LengthValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class LengthValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new LengthValidator(); @@ -52,11 +55,9 @@ class LengthValidatorTest extends ConstraintValidatorTestCase ->assertRaised(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Length(['value' => 5])); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorWithNegativeOrZeroConstraintTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorWithNegativeOrZeroConstraintTest.php index 45ebad541b..2967d82d44 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorWithNegativeOrZeroConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorWithNegativeOrZeroConstraintTest.php @@ -49,40 +49,34 @@ class LessThanOrEqualValidatorWithNegativeOrZeroConstraintTest extends LessThanO ]; } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage The "propertyPath" option of the "Symfony\Component\Validator\Constraints\NegativeOrZero" constraint cannot be set. - */ public function testThrowsConstraintExceptionIfPropertyPath() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('The "propertyPath" option of the "Symfony\Component\Validator\Constraints\NegativeOrZero" constraint cannot be set.'); return new NegativeOrZero(['propertyPath' => 'field']); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage The "value" option of the "Symfony\Component\Validator\Constraints\NegativeOrZero" constraint cannot be set. - */ public function testThrowsConstraintExceptionIfValue() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('The "value" option of the "Symfony\Component\Validator\Constraints\NegativeOrZero" constraint cannot be set.'); return new NegativeOrZero(['value' => 0]); } /** * @dataProvider provideInvalidConstraintOptions - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage requires either the "value" or "propertyPath" option to be set. */ public function testThrowsConstraintExceptionIfNoValueOrPropertyPath($options) { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('requires either the "value" or "propertyPath" option to be set.'); $this->markTestSkipped('Value option always set for NegativeOrZero constraint'); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage requires only one of the "value" or "propertyPath" options to be set, not both. - */ public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('requires only one of the "value" or "propertyPath" options to be set, not both.'); $this->markTestSkipped('Value option is set for NegativeOrZero constraint automatically'); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorWithNegativeConstraintTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorWithNegativeConstraintTest.php index 1a8fff7989..e38bdc4b5e 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorWithNegativeConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorWithNegativeConstraintTest.php @@ -49,40 +49,34 @@ class LessThanValidatorWithNegativeConstraintTest extends LessThanValidatorTest ]; } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage The "propertyPath" option of the "Symfony\Component\Validator\Constraints\Negative" constraint cannot be set. - */ public function testThrowsConstraintExceptionIfPropertyPath() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('The "propertyPath" option of the "Symfony\Component\Validator\Constraints\Negative" constraint cannot be set.'); return new Negative(['propertyPath' => 'field']); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage The "value" option of the "Symfony\Component\Validator\Constraints\Negative" constraint cannot be set. - */ public function testThrowsConstraintExceptionIfValue() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('The "value" option of the "Symfony\Component\Validator\Constraints\Negative" constraint cannot be set.'); return new Negative(['value' => 0]); } /** * @dataProvider provideInvalidConstraintOptions - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage requires either the "value" or "propertyPath" option to be set. */ public function testThrowsConstraintExceptionIfNoValueOrPropertyPath($options) { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('requires either the "value" or "propertyPath" option to be set.'); $this->markTestSkipped('Value option always set for Negative constraint'); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage requires only one of the "value" or "propertyPath" options to be set, not both. - */ public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('requires only one of the "value" or "propertyPath" options to be set, not both.'); $this->markTestSkipped('Value option is set for Negative constraint automatically'); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php index b3ff86ab6f..4f54f2cbdb 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php @@ -11,12 +11,15 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Locale; use Symfony\Component\Validator\Constraints\LocaleValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class LocaleValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new LocaleValidator(); @@ -36,11 +39,9 @@ class LocaleValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Locale()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php index bc69dd78da..997cb7dfe2 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php @@ -11,12 +11,15 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Luhn; use Symfony\Component\Validator\Constraints\LuhnValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class LuhnValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new LuhnValidator(); @@ -99,11 +102,11 @@ class LuhnValidatorTest extends ConstraintValidatorTestCase } /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException * @dataProvider getInvalidTypes */ public function testInvalidTypes($number) { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $constraint = new Luhn(); $this->validator->validate($number, $constraint); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NotBlankTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NotBlankTest.php index af3b047fd8..285132a1f1 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NotBlankTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NotBlankTest.php @@ -26,21 +26,17 @@ class NotBlankTest extends TestCase $this->assertEquals('trim', $notBlank->normalizer); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("string" given). - */ public function testInvalidNormalizerThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new NotBlank(['normalizer' => 'Unknown Callable']); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("stdClass" given). - */ public function testInvalidNormalizerObjectThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new NotBlank(['normalizer' => new \stdClass()]); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NotCompromisedPasswordValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NotCompromisedPasswordValidatorTest.php index f2330b52c7..a0277d45a6 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NotCompromisedPasswordValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NotCompromisedPasswordValidatorTest.php @@ -151,28 +151,22 @@ class NotCompromisedPasswordValidatorTest extends ConstraintValidatorTestCase ->assertRaised(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException - */ public function testInvalidConstraint() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedTypeException'); $this->validator->validate(null, new Luhn()); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException - */ public function testInvalidValue() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedTypeException'); $this->validator->validate([], new NotCompromisedPassword()); } - /** - * @expectedException \Symfony\Contracts\HttpClient\Exception\ExceptionInterface - * @expectedExceptionMessage Problem contacting the Have I been Pwned API. - */ public function testApiError() { + $this->expectException('Symfony\Contracts\HttpClient\Exception\ExceptionInterface'); + $this->expectExceptionMessage('Problem contacting the Have I been Pwned API.'); $this->validator->validate(self::PASSWORD_TRIGGERING_AN_ERROR, new NotCompromisedPassword()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/RangeTest.php b/src/Symfony/Component/Validator/Tests/Constraints/RangeTest.php index b860cb5778..333edada00 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/RangeTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/RangeTest.php @@ -7,45 +7,37 @@ use Symfony\Component\Validator\Constraints\Range; class RangeTest extends TestCase { - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage requires only one of the "min" or "minPropertyPath" options to be set, not both. - */ public function testThrowsConstraintExceptionIfBothMinLimitAndPropertyPath() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('requires only one of the "min" or "minPropertyPath" options to be set, not both.'); new Range([ 'min' => 'min', 'minPropertyPath' => 'minPropertyPath', ]); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage requires only one of the "max" or "maxPropertyPath" options to be set, not both. - */ public function testThrowsConstraintExceptionIfBothMaxLimitAndPropertyPath() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('requires only one of the "max" or "maxPropertyPath" options to be set, not both.'); new Range([ 'max' => 'min', 'maxPropertyPath' => 'maxPropertyPath', ]); } - /** - * @expectedException \Symfony\Component\Validator\Exception\MissingOptionsException - * @expectedExceptionMessage Either option "min", "minPropertyPath", "max" or "maxPropertyPath" must be given - */ public function testThrowsConstraintExceptionIfNoLimitNorPropertyPath() { + $this->expectException('Symfony\Component\Validator\Exception\MissingOptionsException'); + $this->expectExceptionMessage('Either option "min", "minPropertyPath", "max" or "maxPropertyPath" must be given'); new Range([]); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - * @expectedExceptionMessage No default option is configured - */ public function testThrowsNoDefaultOptionConfiguredException() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); + $this->expectExceptionMessage('No default option is configured'); new Range('value'); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/RegexTest.php b/src/Symfony/Component/Validator/Tests/Constraints/RegexTest.php index 53bb257d17..f49f2c0bb4 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/RegexTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/RegexTest.php @@ -93,21 +93,17 @@ class RegexTest extends TestCase $this->assertEquals('trim', $regex->normalizer); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("string" given). - */ public function testInvalidNormalizerThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new Regex(['pattern' => '/^[0-9]+$/', 'normalizer' => 'Unknown Callable']); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("stdClass" given). - */ public function testInvalidNormalizerObjectThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new Regex(['pattern' => '/^[0-9]+$/', 'normalizer' => new \stdClass()]); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php index 9a54af88a8..63ce21b69f 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php @@ -11,12 +11,15 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Regex; use Symfony\Component\Validator\Constraints\RegexValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class RegexValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new RegexValidator(); @@ -36,11 +39,9 @@ class RegexValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Regex(['pattern' => '/^[0-9]+$/'])); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php index da5b4eb9df..f67fdc77b3 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php @@ -11,12 +11,15 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Time; use Symfony\Component\Validator\Constraints\TimeValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class TimeValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new TimeValidator(); @@ -36,11 +39,9 @@ class TimeValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Time()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/TimezoneTest.php b/src/Symfony/Component/Validator/Tests/Constraints/TimezoneTest.php index 450c82ffeb..47566ea6de 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/TimezoneTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/TimezoneTest.php @@ -32,31 +32,27 @@ class TimezoneTest extends TestCase $this->addToAssertionCount(1); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testExceptionForGroupedTimezonesByCountryWithWrongZone() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new Timezone([ 'zone' => \DateTimeZone::ALL, 'countryCode' => 'AR', ]); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testExceptionForGroupedTimezonesByCountryWithoutZone() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new Timezone(['countryCode' => 'AR']); } /** * @dataProvider provideInvalidZones - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException */ public function testExceptionForInvalidGroupedTimezones(int $zone) { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); new Timezone(['zone' => $zone]); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/TimezoneValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/TimezoneValidatorTest.php index 352e45c5d3..1f43224641 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/TimezoneValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/TimezoneValidatorTest.php @@ -40,11 +40,9 @@ class TimezoneValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Timezone()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UniqueValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UniqueValidatorTest.php index 65564abf9c..da46323db3 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UniqueValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UniqueValidatorTest.php @@ -22,11 +22,9 @@ class UniqueValidatorTest extends ConstraintValidatorTestCase return new UniqueValidator(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsUniqueConstraintCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate('', new Unique()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UrlTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UrlTest.php index 6a9c45d417..c1799ed551 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UrlTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UrlTest.php @@ -26,21 +26,17 @@ class UrlTest extends TestCase $this->assertEquals('trim', $url->normalizer); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("string" given). - */ public function testInvalidNormalizerThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new Url(['normalizer' => 'Unknown Callable']); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("stdClass" given). - */ public function testInvalidNormalizerObjectThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new Url(['normalizer' => new \stdClass()]); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php index 4f9daeba5c..5c67c6377b 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php @@ -43,11 +43,9 @@ class UrlValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Url()); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UuidTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UuidTest.php index bfe3d5ed80..e048ecb211 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UuidTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UuidTest.php @@ -26,21 +26,17 @@ class UuidTest extends TestCase $this->assertEquals('trim', $uuid->normalizer); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("string" given). - */ public function testInvalidNormalizerThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); new Uuid(['normalizer' => 'Unknown Callable']); } - /** - * @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException - * @expectedExceptionMessage The "normalizer" option must be a valid callable ("stdClass" given). - */ public function testInvalidNormalizerObjectThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); new Uuid(['normalizer' => new \stdClass()]); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UuidValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UuidValidatorTest.php index 878e5d4234..b50321de1b 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UuidValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UuidValidatorTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Uuid; use Symfony\Component\Validator\Constraints\UuidValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; @@ -20,6 +21,8 @@ use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; */ class UuidValidatorTest extends ConstraintValidatorTestCase { + use ForwardCompatTestTrait; + protected function createValidator() { return new UuidValidator(); @@ -39,21 +42,17 @@ class UuidValidatorTest extends ConstraintValidatorTestCase $this->assertNoViolation(); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException - */ public function testExpectsUuidConstraintCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedTypeException'); $constraint = $this->getMockForAbstractClass('Symfony\\Component\\Validator\\Constraint'); $this->validator->validate('216fff40-98d9-11e3-a5e2-0800200c9a66', $constraint); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException - */ public function testExpectsStringCompatibleType() { + $this->expectException('Symfony\Component\Validator\Exception\UnexpectedValueException'); $this->validator->validate(new \stdClass(), new Uuid()); } diff --git a/src/Symfony/Component/Validator/Tests/ContainerConstraintValidatorFactoryTest.php b/src/Symfony/Component/Validator/Tests/ContainerConstraintValidatorFactoryTest.php index 5178bc3b30..41b0fa8eaa 100644 --- a/src/Symfony/Component/Validator/Tests/ContainerConstraintValidatorFactoryTest.php +++ b/src/Symfony/Component/Validator/Tests/ContainerConstraintValidatorFactoryTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Validator\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\Blank as BlankConstraint; @@ -20,6 +21,8 @@ use Symfony\Component\Validator\ContainerConstraintValidatorFactory; class ContainerConstraintValidatorFactoryTest extends TestCase { + use ForwardCompatTestTrait; + public function testGetInstanceCreatesValidator() { $factory = new ContainerConstraintValidatorFactory(new Container()); @@ -45,11 +48,9 @@ class ContainerConstraintValidatorFactoryTest extends TestCase $this->assertSame($validator, $factory->getInstance(new DummyConstraint())); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ValidatorException - */ public function testGetInstanceInvalidValidatorClass() { + $this->expectException('Symfony\Component\Validator\Exception\ValidatorException'); $constraint = $this->getMockBuilder(Constraint::class)->getMock(); $constraint ->expects($this->once()) diff --git a/src/Symfony/Component/Validator/Tests/DependencyInjection/AddConstraintValidatorsPassTest.php b/src/Symfony/Component/Validator/Tests/DependencyInjection/AddConstraintValidatorsPassTest.php index c3224840bb..48943a3fb2 100644 --- a/src/Symfony/Component/Validator/Tests/DependencyInjection/AddConstraintValidatorsPassTest.php +++ b/src/Symfony/Component/Validator/Tests/DependencyInjection/AddConstraintValidatorsPassTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Validator\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; @@ -21,6 +22,8 @@ use Symfony\Component\Validator\DependencyInjection\AddConstraintValidatorsPass; class AddConstraintValidatorsPassTest extends TestCase { + use ForwardCompatTestTrait; + public function testThatConstraintValidatorServicesAreProcessed() { $container = new ContainerBuilder(); @@ -43,12 +46,10 @@ class AddConstraintValidatorsPassTest extends TestCase $this->assertEquals($expected, $container->getDefinition((string) $validatorFactory->getArgument(0))); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The service "my_abstract_constraint_validator" tagged "validator.constraint_validator" must not be abstract. - */ public function testAbstractConstraintValidator() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The service "my_abstract_constraint_validator" tagged "validator.constraint_validator" must not be abstract.'); $container = new ContainerBuilder(); $container->register('validator.validator_factory') ->addArgument([]); diff --git a/src/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.php b/src/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.php index bb1c2fed0c..e8929d9f81 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.php @@ -253,47 +253,37 @@ class ClassMetadataTest extends TestCase $this->assertInstanceOf('Symfony\Component\Validator\Constraints\GroupSequence', $this->metadata->getGroupSequence()); } - /** - * @expectedException \Symfony\Component\Validator\Exception\GroupDefinitionException - */ public function testGroupSequencesFailIfNotContainingDefaultGroup() { + $this->expectException('Symfony\Component\Validator\Exception\GroupDefinitionException'); $this->metadata->setGroupSequence(['Foo', 'Bar']); } - /** - * @expectedException \Symfony\Component\Validator\Exception\GroupDefinitionException - */ public function testGroupSequencesFailIfContainingDefault() { + $this->expectException('Symfony\Component\Validator\Exception\GroupDefinitionException'); $this->metadata->setGroupSequence(['Foo', $this->metadata->getDefaultGroup(), Constraint::DEFAULT_GROUP]); } - /** - * @expectedException \Symfony\Component\Validator\Exception\GroupDefinitionException - */ public function testGroupSequenceFailsIfGroupSequenceProviderIsSet() { + $this->expectException('Symfony\Component\Validator\Exception\GroupDefinitionException'); $metadata = new ClassMetadata(self::PROVIDERCLASS); $metadata->setGroupSequenceProvider(true); $metadata->setGroupSequence(['GroupSequenceProviderEntity', 'Foo']); } - /** - * @expectedException \Symfony\Component\Validator\Exception\GroupDefinitionException - */ public function testGroupSequenceProviderFailsIfGroupSequenceIsSet() { + $this->expectException('Symfony\Component\Validator\Exception\GroupDefinitionException'); $metadata = new ClassMetadata(self::PROVIDERCLASS); $metadata->setGroupSequence(['GroupSequenceProviderEntity', 'Foo']); $metadata->setGroupSequenceProvider(true); } - /** - * @expectedException \Symfony\Component\Validator\Exception\GroupDefinitionException - */ public function testGroupSequenceProviderFailsIfDomainClassIsInvalid() { + $this->expectException('Symfony\Component\Validator\Exception\GroupDefinitionException'); $metadata = new ClassMetadata('stdClass'); $metadata->setGroupSequenceProvider(true); } diff --git a/src/Symfony/Component/Validator/Tests/Mapping/Factory/BlackHoleMetadataFactoryTest.php b/src/Symfony/Component/Validator/Tests/Mapping/Factory/BlackHoleMetadataFactoryTest.php index 880f6b70d1..87913e8e19 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/Factory/BlackHoleMetadataFactoryTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/Factory/BlackHoleMetadataFactoryTest.php @@ -12,15 +12,16 @@ namespace Symfony\Component\Validator\Tests\Mapping\Factory; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Mapping\Factory\BlackHoleMetadataFactory; class BlackHoleMetadataFactoryTest extends TestCase { - /** - * @expectedException \Symfony\Component\Validator\Exception\LogicException - */ + use ForwardCompatTestTrait; + public function testGetMetadataForThrowsALogicException() { + $this->expectException('Symfony\Component\Validator\Exception\LogicException'); $metadataFactory = new BlackHoleMetadataFactory(); $metadataFactory->getMetadataFor('foo'); } diff --git a/src/Symfony/Component/Validator/Tests/Mapping/Factory/LazyLoadingMetadataFactoryTest.php b/src/Symfony/Component/Validator/Tests/Mapping/Factory/LazyLoadingMetadataFactoryTest.php index 9ad85e3f90..a1f66ce4ce 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/Factory/LazyLoadingMetadataFactoryTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/Factory/LazyLoadingMetadataFactoryTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Validator\Tests\Mapping\Factory; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Validator\Constraints\Callback; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory; @@ -20,6 +21,8 @@ use Symfony\Component\Validator\Tests\Fixtures\ConstraintA; class LazyLoadingMetadataFactoryTest extends TestCase { + use ForwardCompatTestTrait; + const CLASS_NAME = 'Symfony\Component\Validator\Tests\Fixtures\Entity'; const PARENT_CLASS = 'Symfony\Component\Validator\Tests\Fixtures\EntityParent'; const INTERFACE_A_CLASS = 'Symfony\Component\Validator\Tests\Fixtures\EntityInterfaceA'; @@ -149,11 +152,9 @@ class LazyLoadingMetadataFactoryTest extends TestCase $this->assertEquals($metadata, $factory->getMetadataFor(self::PARENT_CLASS)); } - /** - * @expectedException \Symfony\Component\Validator\Exception\NoSuchMetadataException - */ public function testNonClassNameStringValues() { + $this->expectException('Symfony\Component\Validator\Exception\NoSuchMetadataException'); $testedValue = 'error@example.com'; $loader = $this->getMockBuilder('Symfony\Component\Validator\Mapping\Loader\LoaderInterface')->getMock(); $cache = $this->getMockBuilder('Symfony\Component\Validator\Mapping\Cache\CacheInterface')->getMock(); diff --git a/src/Symfony/Component/Validator/Tests/Mapping/GetterMetadataTest.php b/src/Symfony/Component/Validator/Tests/Mapping/GetterMetadataTest.php index fd62ea80f2..7c78a0bb72 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/GetterMetadataTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/GetterMetadataTest.php @@ -64,12 +64,10 @@ class GetterMetadataTest extends TestCase $this->assertEquals('permissions', $metadata->getPropertyValue($entity)); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ValidatorException - * @expectedExceptionMessage The hasLastName() method does not exist in class Symfony\Component\Validator\Tests\Fixtures\Entity. - */ public function testUndefinedMethodNameThrowsException() { + $this->expectException('Symfony\Component\Validator\Exception\ValidatorException'); + $this->expectExceptionMessage('The hasLastName() method does not exist in class Symfony\Component\Validator\Tests\Fixtures\Entity.'); new GetterMetadata(self::CLASSNAME, 'lastName', 'hasLastName'); } } diff --git a/src/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.php index 158bebdbc7..d30a83d8b8 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.php @@ -43,10 +43,10 @@ class YamlFileLoaderTest extends TestCase /** * @dataProvider provideInvalidYamlFiles - * @expectedException \InvalidArgumentException */ public function testInvalidYamlFiles($path) { + $this->expectException('InvalidArgumentException'); $loader = new YamlFileLoader(__DIR__.'/'.$path); $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity'); diff --git a/src/Symfony/Component/Validator/Tests/Validator/AbstractTest.php b/src/Symfony/Component/Validator/Tests/Validator/AbstractTest.php index a2525311c5..85b81ebe52 100644 --- a/src/Symfony/Component/Validator/Tests/Validator/AbstractTest.php +++ b/src/Symfony/Component/Validator/Tests/Validator/AbstractTest.php @@ -414,11 +414,9 @@ abstract class AbstractTest extends AbstractValidatorTest $this->assertCount(0, $violations); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException - */ public function testExpectTraversableIfTraversalEnabledOnClass() { + $this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); $entity = new Entity(); $this->metadata->addConstraint(new Traverse(true)); @@ -572,11 +570,9 @@ abstract class AbstractTest extends AbstractValidatorTest $this->assertCount(1, $violations); } - /** - * @expectedException \Symfony\Component\Validator\Exception\RuntimeException - */ public function testValidateFailsIfNoConstraintsAndNoObjectOrArray() { + $this->expectException('Symfony\Component\Validator\Exception\RuntimeException'); $this->validate('Foobar'); } diff --git a/src/Symfony/Component/Validator/Tests/Validator/AbstractValidatorTest.php b/src/Symfony/Component/Validator/Tests/Validator/AbstractValidatorTest.php index e07a158fa2..9d345b763a 100644 --- a/src/Symfony/Component/Validator/Tests/Validator/AbstractValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Validator/AbstractValidatorTest.php @@ -502,11 +502,9 @@ abstract class AbstractValidatorTest extends TestCase $this->assertCount(0, $violations); } - /** - * @expectedException \Symfony\Component\Validator\Exception\NoSuchMetadataException - */ public function testFailOnScalarReferences() { + $this->expectException('Symfony\Component\Validator\Exception\NoSuchMetadataException'); $entity = new Entity(); $entity->reference = 'string'; @@ -741,11 +739,9 @@ abstract class AbstractValidatorTest extends TestCase $this->assertCount(0, $violations); } - /** - * @expectedException \Symfony\Component\Validator\Exception\NoSuchMetadataException - */ public function testMetadataMustExistIfTraversalIsDisabled() { + $this->expectException('Symfony\Component\Validator\Exception\NoSuchMetadataException'); $entity = new Entity(); $entity->reference = new \ArrayIterator(); diff --git a/src/Symfony/Component/VarExporter/Tests/InstantiatorTest.php b/src/Symfony/Component/VarExporter/Tests/InstantiatorTest.php index cae10e3b44..3da602383f 100644 --- a/src/Symfony/Component/VarExporter/Tests/InstantiatorTest.php +++ b/src/Symfony/Component/VarExporter/Tests/InstantiatorTest.php @@ -16,22 +16,20 @@ use Symfony\Component\VarExporter\Instantiator; class InstantiatorTest extends TestCase { - /** - * @expectedException \Symfony\Component\VarExporter\Exception\ClassNotFoundException - * @expectedExceptionMessage Class "SomeNotExistingClass" not found. - */ public function testNotFoundClass() { + $this->expectException('Symfony\Component\VarExporter\Exception\ClassNotFoundException'); + $this->expectExceptionMessage('Class "SomeNotExistingClass" not found.'); Instantiator::instantiate('SomeNotExistingClass'); } /** * @dataProvider provideFailingInstantiation - * @expectedException \Symfony\Component\VarExporter\Exception\NotInstantiableTypeException - * @expectedExceptionMessageRegexp Type ".*" is not instantiable. */ public function testFailingInstantiation(string $class) { + $this->expectException('Symfony\Component\VarExporter\Exception\NotInstantiableTypeException'); + $this->expectExceptionMessageRegExp('/Type ".*" is not instantiable\./'); Instantiator::instantiate($class); } diff --git a/src/Symfony/Component/VarExporter/Tests/VarExporterTest.php b/src/Symfony/Component/VarExporter/Tests/VarExporterTest.php index 78ef7ed80a..d929b6ebdd 100644 --- a/src/Symfony/Component/VarExporter/Tests/VarExporterTest.php +++ b/src/Symfony/Component/VarExporter/Tests/VarExporterTest.php @@ -20,12 +20,10 @@ class VarExporterTest extends TestCase { use VarDumperTestTrait; - /** - * @expectedException \Symfony\Component\VarExporter\Exception\ClassNotFoundException - * @expectedExceptionMessage Class "SomeNotExistingClass" not found. - */ public function testPhpIncompleteClassesAreForbidden() { + $this->expectException('Symfony\Component\VarExporter\Exception\ClassNotFoundException'); + $this->expectExceptionMessage('Class "SomeNotExistingClass" not found.'); $unserializeCallback = ini_set('unserialize_callback_func', 'var_dump'); try { Registry::unserialize([], ['O:20:"SomeNotExistingClass":0:{}']); @@ -36,11 +34,11 @@ class VarExporterTest extends TestCase /** * @dataProvider provideFailingSerialization - * @expectedException \Symfony\Component\VarExporter\Exception\NotInstantiableTypeException - * @expectedExceptionMessageRegexp Type ".*" is not instantiable. */ public function testFailingSerialization($value) { + $this->expectException('Symfony\Component\VarExporter\Exception\NotInstantiableTypeException'); + $this->expectExceptionMessageRegExp('/Type ".*" is not instantiable\./'); $expectedDump = $this->getDump($value); try { VarExporter::export($value); diff --git a/src/Symfony/Component/Workflow/Tests/DefinitionTest.php b/src/Symfony/Component/Workflow/Tests/DefinitionTest.php index 8bbac4a8c7..42abfed487 100644 --- a/src/Symfony/Component/Workflow/Tests/DefinitionTest.php +++ b/src/Symfony/Component/Workflow/Tests/DefinitionTest.php @@ -3,11 +3,14 @@ namespace Symfony\Component\Workflow\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Workflow\Definition; use Symfony\Component\Workflow\Transition; class DefinitionTest extends TestCase { + use ForwardCompatTestTrait; + public function testAddPlaces() { $places = range('a', 'e'); @@ -34,12 +37,10 @@ class DefinitionTest extends TestCase $this->assertEquals(['a', 'e'], $definition->getInitialPlaces()); } - /** - * @expectedException \Symfony\Component\Workflow\Exception\LogicException - * @expectedExceptionMessage Place "d" cannot be the initial place as it does not exist. - */ public function testSetInitialPlaceAndPlaceIsNotDefined() { + $this->expectException('Symfony\Component\Workflow\Exception\LogicException'); + $this->expectExceptionMessage('Place "d" cannot be the initial place as it does not exist.'); $definition = new Definition([], [], 'd'); } @@ -54,23 +55,19 @@ class DefinitionTest extends TestCase $this->assertSame($transition, $definition->getTransitions()[0]); } - /** - * @expectedException \Symfony\Component\Workflow\Exception\LogicException - * @expectedExceptionMessage Place "c" referenced in transition "name" does not exist. - */ public function testAddTransitionAndFromPlaceIsNotDefined() { + $this->expectException('Symfony\Component\Workflow\Exception\LogicException'); + $this->expectExceptionMessage('Place "c" referenced in transition "name" does not exist.'); $places = range('a', 'b'); new Definition($places, [new Transition('name', 'c', $places[1])]); } - /** - * @expectedException \Symfony\Component\Workflow\Exception\LogicException - * @expectedExceptionMessage Place "c" referenced in transition "name" does not exist. - */ public function testAddTransitionAndToPlaceIsNotDefined() { + $this->expectException('Symfony\Component\Workflow\Exception\LogicException'); + $this->expectExceptionMessage('Place "c" referenced in transition "name" does not exist.'); $places = range('a', 'b'); new Definition($places, [new Transition('name', $places[0], 'c')]); diff --git a/src/Symfony/Component/Workflow/Tests/Metadata/InMemoryMetadataStoreTest.php b/src/Symfony/Component/Workflow/Tests/Metadata/InMemoryMetadataStoreTest.php index 16d2d6f20c..5e5c8fec6f 100644 --- a/src/Symfony/Component/Workflow/Tests/Metadata/InMemoryMetadataStoreTest.php +++ b/src/Symfony/Component/Workflow/Tests/Metadata/InMemoryMetadataStoreTest.php @@ -75,12 +75,10 @@ class InMemoryMetadataStoreTest extends TestCase $this->assertNull($this->store->getMetadata('description', new Transition('transition_2', [], []))); } - /** - * @expectedException \Symfony\Component\Workflow\Exception\InvalidArgumentException - * @expectedExceptionMessage Could not find a MetadataBag for the subject of type "boolean". - */ public function testGetMetadataWithUnknownType() { + $this->expectException('Symfony\Component\Workflow\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Could not find a MetadataBag for the subject of type "boolean".'); $this->store->getMetadata('title', true); } } diff --git a/src/Symfony/Component/Workflow/Tests/RegistryTest.php b/src/Symfony/Component/Workflow/Tests/RegistryTest.php index 9c5d98d0c3..a04db9af82 100644 --- a/src/Symfony/Component/Workflow/Tests/RegistryTest.php +++ b/src/Symfony/Component/Workflow/Tests/RegistryTest.php @@ -46,23 +46,19 @@ class RegistryTest extends TestCase $this->assertSame('workflow2', $workflow->getName()); } - /** - * @expectedException \Symfony\Component\Workflow\Exception\InvalidArgumentException - * @expectedExceptionMessage At least two workflows match this subject. Set a different name on each and use the second (name) argument of this method. - */ public function testGetWithMultipleMatch() { + $this->expectException('Symfony\Component\Workflow\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('At least two workflows match this subject. Set a different name on each and use the second (name) argument of this method.'); $w1 = $this->registry->get(new Subject2()); $this->assertInstanceOf(Workflow::class, $w1); $this->assertSame('workflow1', $w1->getName()); } - /** - * @expectedException \Symfony\Component\Workflow\Exception\InvalidArgumentException - * @expectedExceptionMessage Unable to find a workflow for class "stdClass". - */ public function testGetWithNoMatch() { + $this->expectException('Symfony\Component\Workflow\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Unable to find a workflow for class "stdClass".'); $w1 = $this->registry->get(new \stdClass()); $this->assertInstanceOf(Workflow::class, $w1); $this->assertSame('workflow1', $w1->getName()); diff --git a/src/Symfony/Component/Workflow/Tests/TransitionTest.php b/src/Symfony/Component/Workflow/Tests/TransitionTest.php index 14a646d509..2b70ae0758 100644 --- a/src/Symfony/Component/Workflow/Tests/TransitionTest.php +++ b/src/Symfony/Component/Workflow/Tests/TransitionTest.php @@ -3,10 +3,13 @@ namespace Symfony\Component\Workflow\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Workflow\Transition; class TransitionTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $transition = new Transition('name', 'a', 'b'); diff --git a/src/Symfony/Component/Workflow/Tests/Validator/StateMachineValidatorTest.php b/src/Symfony/Component/Workflow/Tests/Validator/StateMachineValidatorTest.php index 35da1f2ec8..3469e91fdf 100644 --- a/src/Symfony/Component/Workflow/Tests/Validator/StateMachineValidatorTest.php +++ b/src/Symfony/Component/Workflow/Tests/Validator/StateMachineValidatorTest.php @@ -3,18 +3,19 @@ namespace Symfony\Component\Workflow\Tests\Validator; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Workflow\Definition; use Symfony\Component\Workflow\Transition; use Symfony\Component\Workflow\Validator\StateMachineValidator; class StateMachineValidatorTest extends TestCase { - /** - * @expectedException \Symfony\Component\Workflow\Exception\InvalidDefinitionException - * @expectedExceptionMessage A transition from a place/state must have an unique name. - */ + use ForwardCompatTestTrait; + public function testWithMultipleTransitionWithSameNameShareInput() { + $this->expectException('Symfony\Component\Workflow\Exception\InvalidDefinitionException'); + $this->expectExceptionMessage('A transition from a place/state must have an unique name.'); $places = ['a', 'b', 'c']; $transitions[] = new Transition('t1', 'a', 'b'); $transitions[] = new Transition('t1', 'a', 'c'); @@ -35,12 +36,10 @@ class StateMachineValidatorTest extends TestCase // +----+ +----+ } - /** - * @expectedException \Symfony\Component\Workflow\Exception\InvalidDefinitionException - * @expectedExceptionMessage A transition in StateMachine can only have one output. - */ public function testWithMultipleTos() { + $this->expectException('Symfony\Component\Workflow\Exception\InvalidDefinitionException'); + $this->expectExceptionMessage('A transition in StateMachine can only have one output.'); $places = ['a', 'b', 'c']; $transitions[] = new Transition('t1', 'a', ['b', 'c']); $definition = new Definition($places, $transitions); @@ -60,12 +59,10 @@ class StateMachineValidatorTest extends TestCase // +----+ } - /** - * @expectedException \Symfony\Component\Workflow\Exception\InvalidDefinitionException - * @expectedExceptionMessage A transition in StateMachine can only have one input. - */ public function testWithMultipleFroms() { + $this->expectException('Symfony\Component\Workflow\Exception\InvalidDefinitionException'); + $this->expectExceptionMessage('A transition in StateMachine can only have one input.'); $places = ['a', 'b', 'c']; $transitions[] = new Transition('t1', ['a', 'b'], 'c'); $definition = new Definition($places, $transitions); @@ -110,12 +107,10 @@ class StateMachineValidatorTest extends TestCase // +----+ +----+ } - /** - * @expectedException \Symfony\Component\Workflow\Exception\InvalidDefinitionException - * @expectedExceptionMessage The state machine "foo" can not store many places. But the definition has 2 initial places. Only one is supported. - */ public function testWithTooManyInitialPlaces() { + $this->expectException('Symfony\Component\Workflow\Exception\InvalidDefinitionException'); + $this->expectExceptionMessage('The state machine "foo" can not store many places. But the definition has 2 initial places. Only one is supported.'); $places = range('a', 'c'); $transitions = []; $definition = new Definition($places, $transitions, ['a', 'b']); diff --git a/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php b/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php index 2877947a91..487768193b 100644 --- a/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php +++ b/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php @@ -3,6 +3,7 @@ namespace Symfony\Component\Workflow\Tests\Validator; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Workflow\Definition; use Symfony\Component\Workflow\Tests\WorkflowBuilderTrait; use Symfony\Component\Workflow\Transition; @@ -10,14 +11,13 @@ use Symfony\Component\Workflow\Validator\WorkflowValidator; class WorkflowValidatorTest extends TestCase { + use ForwardCompatTestTrait; use WorkflowBuilderTrait; - /** - * @expectedException \Symfony\Component\Workflow\Exception\InvalidDefinitionException - * @expectedExceptionMessage All transitions for a place must have an unique name. Multiple transitions named "t1" where found for place "a" in workflow "foo". - */ public function testWorkflowWithInvalidNames() { + $this->expectException('Symfony\Component\Workflow\Exception\InvalidDefinitionException'); + $this->expectExceptionMessage('All transitions for a place must have an unique name. Multiple transitions named "t1" where found for place "a" in workflow "foo".'); $places = range('a', 'c'); $transitions = []; diff --git a/src/Symfony/Component/Workflow/Tests/WorkflowTest.php b/src/Symfony/Component/Workflow/Tests/WorkflowTest.php index 9a8f97d94a..07e17f5781 100644 --- a/src/Symfony/Component/Workflow/Tests/WorkflowTest.php +++ b/src/Symfony/Component/Workflow/Tests/WorkflowTest.php @@ -3,6 +3,7 @@ namespace Symfony\Component\Workflow\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Workflow\Definition; use Symfony\Component\Workflow\Event\Event; @@ -18,38 +19,33 @@ use Symfony\Component\Workflow\Workflow; class WorkflowTest extends TestCase { + use ForwardCompatTestTrait; use WorkflowBuilderTrait; - /** - * @expectedException \Symfony\Component\Workflow\Exception\LogicException - * @expectedExceptionMessage The value returned by the MarkingStore is not an instance of "Symfony\Component\Workflow\Marking" for workflow "unnamed". - */ public function testGetMarkingWithInvalidStoreReturn() { + $this->expectException('Symfony\Component\Workflow\Exception\LogicException'); + $this->expectExceptionMessage('The value returned by the MarkingStore is not an instance of "Symfony\Component\Workflow\Marking" for workflow "unnamed".'); $subject = new Subject(); $workflow = new Workflow(new Definition([], []), $this->getMockBuilder(MarkingStoreInterface::class)->getMock()); $workflow->getMarking($subject); } - /** - * @expectedException \Symfony\Component\Workflow\Exception\LogicException - * @expectedExceptionMessage The Marking is empty and there is no initial place for workflow "unnamed". - */ public function testGetMarkingWithEmptyDefinition() { + $this->expectException('Symfony\Component\Workflow\Exception\LogicException'); + $this->expectExceptionMessage('The Marking is empty and there is no initial place for workflow "unnamed".'); $subject = new Subject(); $workflow = new Workflow(new Definition([], []), new MethodMarkingStore()); $workflow->getMarking($subject); } - /** - * @expectedException \Symfony\Component\Workflow\Exception\LogicException - * @expectedExceptionMessage Place "nope" is not valid for workflow "unnamed". - */ public function testGetMarkingWithImpossiblePlace() { + $this->expectException('Symfony\Component\Workflow\Exception\LogicException'); + $this->expectExceptionMessage('Place "nope" is not valid for workflow "unnamed".'); $subject = new Subject(); $subject->setMarking(['nope' => 1]); $workflow = new Workflow(new Definition([], []), new MethodMarkingStore()); @@ -173,12 +169,10 @@ class WorkflowTest extends TestCase $this->assertTrue($workflow->can($subject, 'to_a')); } - /** - * @expectedException \Symfony\Component\Workflow\Exception\UndefinedTransitionException - * @expectedExceptionMessage Transition "404 Not Found" is not defined for workflow "unnamed". - */ public function testBuildTransitionBlockerListReturnsUndefinedTransition() { + $this->expectException('Symfony\Component\Workflow\Exception\UndefinedTransitionException'); + $this->expectExceptionMessage('Transition "404 Not Found" is not defined for workflow "unnamed".'); $definition = $this->createSimpleWorkflowDefinition(); $subject = new Subject(); $workflow = new Workflow($definition, new MethodMarkingStore()); @@ -255,12 +249,10 @@ class WorkflowTest extends TestCase $this->assertSame('e8b5bbb9-5913-4b98-bfa6-65dbd228a82a', $blockers[3]->getCode()); } - /** - * @expectedException \Symfony\Component\Workflow\Exception\UndefinedTransitionException - * @expectedExceptionMessage Transition "404 Not Found" is not defined for workflow "unnamed". - */ public function testApplyWithNotExisingTransition() { + $this->expectException('Symfony\Component\Workflow\Exception\UndefinedTransitionException'); + $this->expectExceptionMessage('Transition "404 Not Found" is not defined for workflow "unnamed".'); $definition = $this->createComplexWorkflowDefinition(); $subject = new Subject(); $workflow = new Workflow($definition, new MethodMarkingStore()); diff --git a/src/Symfony/Component/Yaml/Tests/Command/LintCommandTest.php b/src/Symfony/Component/Yaml/Tests/Command/LintCommandTest.php index 2087fb8946..0e0ff7e94d 100644 --- a/src/Symfony/Component/Yaml/Tests/Command/LintCommandTest.php +++ b/src/Symfony/Component/Yaml/Tests/Command/LintCommandTest.php @@ -93,11 +93,9 @@ YAML; $this->assertSame(1, $ret, 'lint:yaml exits with code 1 in case of error'); } - /** - * @expectedException \RuntimeException - */ public function testLintFileNotReadable() { + $this->expectException('RuntimeException'); $tester = $this->createCommandTester(); $filename = $this->createFile(''); unlink($filename); diff --git a/src/Symfony/Component/Yaml/Tests/DumperTest.php b/src/Symfony/Component/Yaml/Tests/DumperTest.php index 24d956b09b..c761c68dc7 100644 --- a/src/Symfony/Component/Yaml/Tests/DumperTest.php +++ b/src/Symfony/Component/Yaml/Tests/DumperTest.php @@ -195,11 +195,9 @@ EOF; $this->assertEquals('{ foo: null, bar: 1 }', $dump, '->dump() does not dump objects when disabled'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\DumpException - */ public function testObjectSupportDisabledWithExceptions() { + $this->expectException('Symfony\Component\Yaml\Exception\DumpException'); $this->dumper->dump(['foo' => new A(), 'bar' => 1], 0, 0, Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE); } @@ -496,21 +494,17 @@ YAML; $this->assertSame("- \"a\\r\\nb\\nc\"\n", $this->dumper->dump(["a\r\nb\nc"], 2, 0, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK)); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The indentation must be greater than zero - */ public function testZeroIndentationThrowsException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The indentation must be greater than zero'); new Dumper(0); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The indentation must be greater than zero - */ public function testNegativeIndentationThrowsException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The indentation must be greater than zero'); new Dumper(-4); } } diff --git a/src/Symfony/Component/Yaml/Tests/InlineTest.php b/src/Symfony/Component/Yaml/Tests/InlineTest.php index 5a6cfda851..2dcf9ddbab 100644 --- a/src/Symfony/Component/Yaml/Tests/InlineTest.php +++ b/src/Symfony/Component/Yaml/Tests/InlineTest.php @@ -66,21 +66,17 @@ class InlineTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage The constant "WRONG_CONSTANT" is not defined - */ public function testParsePhpConstantThrowsExceptionWhenUndefined() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('The constant "WRONG_CONSTANT" is not defined'); Inline::parse('!php/const WRONG_CONSTANT', Yaml::PARSE_CONSTANT); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessageRegExp #The string "!php/const PHP_INT_MAX" could not be parsed as a constant.*# - */ public function testParsePhpConstantThrowsExceptionOnInvalidType() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessageRegExp('#The string "!php/const PHP_INT_MAX" could not be parsed as a constant.*#'); Inline::parse('!php/const PHP_INT_MAX', Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE); } @@ -121,72 +117,56 @@ class InlineTest extends TestCase $this->assertSame($value, Inline::parse(Inline::dump($value))); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Found unknown escape character "\V". - */ public function testParseScalarWithNonEscapedBlackslashShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Found unknown escape character "\V".'); Inline::parse('"Foo\Var"'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testParseScalarWithNonEscapedBlackslashAtTheEndShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); Inline::parse('"Foo\\"'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testParseScalarWithIncorrectlyQuotedStringShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $value = "'don't do somthin' like that'"; Inline::parse($value); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testParseScalarWithIncorrectlyDoubleQuotedStringShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $value = '"don"t do somthin" like that"'; Inline::parse($value); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testParseInvalidMappingKeyShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $value = '{ "foo " bar": "bar" }'; Inline::parse($value); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Colons must be followed by a space or an indication character (i.e. " ", ",", "[", "]", "{", "}") - */ public function testParseMappingKeyWithColonNotFollowedBySpace() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Colons must be followed by a space or an indication character (i.e. " ", ",", "[", "]", "{", "}")'); Inline::parse('{foo:""}'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testParseInvalidMappingShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); Inline::parse('[foo] bar'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testParseInvalidSequenceShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); Inline::parse('{ foo: bar } bar'); } @@ -230,21 +210,17 @@ class InlineTest extends TestCase $this->assertSame([$foo], Inline::parse('[*foo]', 0, ['foo' => $foo])); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage A reference must contain at least one character at line 1. - */ public function testParseUnquotedAsterisk() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('A reference must contain at least one character at line 1.'); Inline::parse('{ foo: * }'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage A reference must contain at least one character at line 1. - */ public function testParseUnquotedAsteriskFollowedByAComment() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('A reference must contain at least one character at line 1.'); Inline::parse('{ foo: * #foo }'); } @@ -615,10 +591,10 @@ class InlineTest extends TestCase /** * @dataProvider getInvalidBinaryData - * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ public function testParseInvalidBinaryData($data, $expectedMessage) { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $this->expectExceptionMessageRegExp($expectedMessage); Inline::parse($data); @@ -634,12 +610,10 @@ class InlineTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Malformed inline YAML string: {this, is not, supported} at line 1. - */ public function testNotSupportedMissingValue() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Malformed inline YAML string: {this, is not, supported} at line 1.'); Inline::parse('{this, is not, supported}'); } @@ -653,12 +627,10 @@ class InlineTest extends TestCase $this->assertEquals($longStringWithQuotes, $arrayFromYaml['longStringWithQuotes']); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Missing mapping key - */ public function testMappingKeysCannotBeOmitted() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Missing mapping key'); Inline::parse('{: foo}'); } @@ -684,13 +656,13 @@ class InlineTest extends TestCase } /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Implicit casting of incompatible mapping keys to strings is not supported. Quote your evaluable mapping keys instead * * @dataProvider getNotPhpCompatibleMappingKeyData */ public function testImplicitStringCastingOfMappingKeysIsDeprecated($yaml, $expected) { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Implicit casting of incompatible mapping keys to strings is not supported. Quote your evaluable mapping keys instead'); $this->assertSame($expected, Inline::parse($yaml)); } @@ -740,12 +712,10 @@ class InlineTest extends TestCase $this->assertSame('', $value['foo']->getValue()); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Unexpected end of line, expected one of ",}" at line 1 (near "{abc: 'def'"). - */ public function testUnfinishedInlineMap() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Unexpected end of line, expected one of ",}" at line 1 (near "{abc: \'def\'").'); Inline::parse("{abc: 'def'"); } } diff --git a/src/Symfony/Component/Yaml/Tests/ParserTest.php b/src/Symfony/Component/Yaml/Tests/ParserTest.php index b1db699759..5565af126d 100644 --- a/src/Symfony/Component/Yaml/Tests/ParserTest.php +++ b/src/Symfony/Component/Yaml/Tests/ParserTest.php @@ -515,11 +515,9 @@ YAML; return $tests; } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testObjectsSupportDisabledWithExceptions() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $yaml = <<<'EOF' foo: !php/object:O:30:"Symfony\Tests\Component\Yaml\B":1:{s:1:"b";s:3:"foo";} bar: 1 @@ -528,12 +526,11 @@ EOF; $this->parser->parse($yaml, Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Mapping values are not allowed in multi-line blocks at line 2 (near "dbal:wrong"). - */ public function testMappingKeyInMultiLineStringTriggersDeprecationNotice() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Mapping values are not allowed in multi-line blocks at line 2 (near "dbal:wrong").'); + $yaml = <<<'EOF' data: dbal:wrong @@ -575,11 +572,9 @@ EOF; } } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testUnindentedCollectionException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $yaml = <<<'EOF' collection: @@ -592,11 +587,9 @@ EOF; $this->parser->parse($yaml); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testShortcutKeyUnindentedCollectionException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $yaml = <<<'EOF' collection: @@ -608,12 +601,10 @@ EOF; $this->parser->parse($yaml); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessageRegExp /^Multiple documents are not supported.+/ - */ public function testMultipleDocumentsNotSupportedException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessageRegExp('/^Multiple documents are not supported.+/'); Yaml::parse(<<<'EOL' # Ranking of 1998 home runs --- @@ -629,11 +620,9 @@ EOL ); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testSequenceInAMapping() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); Yaml::parse(<<<'EOF' yaml: hash: me @@ -738,10 +727,10 @@ EOT; /** * @dataProvider getParseExceptionNotAffectedMultiLineStringLastResortParsing - * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ public function testParseExceptionNotAffectedByMultiLineStringLastResortParsing($yaml) { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $this->parser->parse($yaml); } @@ -771,11 +760,9 @@ EOT; $this->assertSame($expected, $this->parser->parse($yaml)); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testMappingInASequence() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); Yaml::parse(<<<'EOF' yaml: - array stuff @@ -784,12 +771,10 @@ EOF ); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage missing colon - */ public function testScalarInSequence() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('missing colon'); Yaml::parse(<<<'EOF' foo: - bar @@ -800,8 +785,6 @@ EOF } /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Duplicate key "child" detected * * > It is an error for two equal keys to appear in the same mapping node. * > In such a case the YAML processor may continue, ignoring the second @@ -814,6 +797,8 @@ EOF */ public function testMappingDuplicateKeyBlock() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Duplicate key "child" detected'); $input = <<<'EOD' parent: child: first @@ -830,12 +815,10 @@ EOD; $this->assertSame($expected, Yaml::parse($input)); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Duplicate key "child" detected - */ public function testMappingDuplicateKeyFlow() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Duplicate key "child" detected'); $input = <<<'EOD' parent: { child: first, child: duplicate } parent: { child: duplicate, child: duplicate } @@ -849,11 +832,11 @@ EOD; } /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException * @dataProvider getParseExceptionOnDuplicateData */ public function testParseExceptionOnDuplicate($input, $duplicateKey, $lineNumber) { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $this->expectExceptionMessage(sprintf('Duplicate key "%s" detected at line %d', $duplicateKey, $lineNumber)); Yaml::parse($input); @@ -1077,12 +1060,10 @@ EOF; $this->assertEquals(['foo' => 1, 'bar' => 2], $this->parser->parse($yaml)); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Numeric keys are not supported. Quote your evaluable mapping keys instead - */ public function testFloatKeys() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Numeric keys are not supported. Quote your evaluable mapping keys instead'); $yaml = <<<'EOF' foo: 1.2: "bar" @@ -1092,12 +1073,10 @@ EOF; $this->parser->parse($yaml); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Non-string keys are not supported. Quote your evaluable mapping keys instead - */ public function testBooleanKeys() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Non-string keys are not supported. Quote your evaluable mapping keys instead'); $yaml = <<<'EOF' true: foo false: bar @@ -1131,12 +1110,10 @@ EOF; $this->assertEquals($expected, $this->parser->parse($yaml)); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage A colon cannot be used in an unquoted mapping value - */ public function testColonInMappingValueException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('A colon cannot be used in an unquoted mapping value'); $yaml = <<<'EOF' foo: bar: baz EOF; @@ -1370,10 +1347,10 @@ EOT /** * @dataProvider getInvalidBinaryData - * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ public function testParseInvalidBinaryData($data, $expectedMessage) { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $this->expectExceptionMessageRegExp($expectedMessage); $this->parser->parse($data); @@ -1705,48 +1682,38 @@ YAML $this->assertSame('12', $this->parser->parse('! 12')); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Tags support is not enabled. Enable the "Yaml::PARSE_CUSTOM_TAGS" flag to use "!iterator" at line 1 (near "!iterator [foo]"). - */ public function testCustomTagsDisabled() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Tags support is not enabled. Enable the "Yaml::PARSE_CUSTOM_TAGS" flag to use "!iterator" at line 1 (near "!iterator [foo]").'); $this->parser->parse('!iterator [foo]'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Tags support is not enabled. Enable the "Yaml::PARSE_CUSTOM_TAGS" flag to use "!iterator" at line 1 (near "!iterator foo"). - */ public function testUnsupportedTagWithScalar() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Tags support is not enabled. Enable the "Yaml::PARSE_CUSTOM_TAGS" flag to use "!iterator" at line 1 (near "!iterator foo").'); $this->parser->parse('!iterator foo'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage The string "!!iterator foo" could not be parsed as it uses an unsupported built-in tag at line 1 (near "!!iterator foo"). - */ public function testUnsupportedBuiltInTagWithScalar() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('The string "!!iterator foo" could not be parsed as it uses an unsupported built-in tag at line 1 (near "!!iterator foo").'); $this->parser->parse('!!iterator foo'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage The built-in tag "!!foo" is not implemented at line 1 (near "!!foo"). - */ public function testExceptionWhenUsingUnsuportedBuiltInTags() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('The built-in tag "!!foo" is not implemented at line 1 (near "!!foo").'); $this->parser->parse('!!foo'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Complex mappings are not supported at line 1 (near "? "1""). - */ public function testComplexMappingThrowsParseException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Complex mappings are not supported at line 1 (near "? "1"").'); $yaml = <<parser->parse($yaml); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Complex mappings are not supported at line 2 (near "? "1""). - */ public function testComplexMappingNestedInMappingThrowsParseException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Complex mappings are not supported at line 2 (near "? "1"").'); $yaml = <<parser->parse($yaml); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Complex mappings are not supported at line 1 (near "- ? "1""). - */ public function testComplexMappingNestedInSequenceThrowsParseException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Complex mappings are not supported at line 1 (near "- ? "1"").'); $yaml = <<parser->parse($yaml); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Unable to parse at line 1 (near "[parameters]"). - */ public function testParsingIniThrowsException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Unable to parse at line 1 (near "[parameters]").'); $ini = <<assertEquals($trickyVal, $arrayFromYaml); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Reference "foo" does not exist at line 2 - */ public function testParserCleansUpReferencesBetweenRuns() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Reference "foo" does not exist at line 2'); $yaml = <<assertIsArray($this->parser->parseFile(__DIR__.'/Fixtures/index.yml')); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessageRegExp #^File ".+/Fixtures/nonexistent.yml" does not exist\.$# - */ public function testParsingNonExistentFilesThrowsException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessageRegExp('#^File ".+/Fixtures/nonexistent.yml" does not exist\.$#'); $this->parser->parseFile(__DIR__.'/Fixtures/nonexistent.yml'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessageRegExp #^File ".+/Fixtures/not_readable.yml" cannot be read\.$# - */ public function testParsingNotReadableFilesThrowsException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessageRegExp('#^File ".+/Fixtures/not_readable.yml" cannot be read\.$#'); if ('\\' === \DIRECTORY_SEPARATOR) { $this->markTestSkipped('chmod is not supported on Windows'); } @@ -2020,12 +1975,10 @@ YAML; $this->assertEquals($expected, $this->parser->parse($yaml, Yaml::PARSE_OBJECT_FOR_MAP)); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Reference "foo" does not exist - */ public function testEvalRefException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Reference "foo" does not exist'); $yaml = <<expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Circular reference [foo, bar, foo] detected'); $this->parser->parse($yaml, Yaml::PARSE_CUSTOM_TAGS); } diff --git a/src/Symfony/Component/Yaml/Tests/YamlTest.php b/src/Symfony/Component/Yaml/Tests/YamlTest.php index 5a792c5116..158d581d66 100644 --- a/src/Symfony/Component/Yaml/Tests/YamlTest.php +++ b/src/Symfony/Component/Yaml/Tests/YamlTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\Yaml\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\Yaml\Yaml; class YamlTest extends TestCase { + use ForwardCompatTestTrait; + public function testParseAndDump() { $data = ['lorem' => 'ipsum', 'dolor' => 'sit']; @@ -24,21 +27,17 @@ class YamlTest extends TestCase $this->assertEquals($data, $parsed); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The indentation must be greater than zero - */ public function testZeroIndentationThrowsException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The indentation must be greater than zero'); Yaml::dump(['lorem' => 'ipsum', 'dolor' => 'sit'], 2, 0); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The indentation must be greater than zero - */ public function testNegativeIndentationThrowsException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The indentation must be greater than zero'); Yaml::dump(['lorem' => 'ipsum', 'dolor' => 'sit'], 2, -4); } } diff --git a/src/Symfony/Contracts/Service/Test/ServiceLocatorTest.php b/src/Symfony/Contracts/Service/Test/ServiceLocatorTest.php index 69594583f5..408c017c3e 100644 --- a/src/Symfony/Contracts/Service/Test/ServiceLocatorTest.php +++ b/src/Symfony/Contracts/Service/Test/ServiceLocatorTest.php @@ -64,12 +64,12 @@ class ServiceLocatorTest extends TestCase $this->assertSame(2, $i); } - /** - * @expectedException \Psr\Container\NotFoundExceptionInterface - * @expectedExceptionMessage The service "foo" has a dependency on a non-existent service "bar". This locator only knows about the "foo" service. - */ public function testThrowsOnUndefinedInternalService() { + if (!$this->getExpectedException()) { + $this->expectException('Psr\Container\NotFoundExceptionInterface'); + $this->expectExceptionMessage('The service "foo" has a dependency on a non-existent service "bar". This locator only knows about the "foo" service.'); + } $locator = $this->getServiceLocator([ 'foo' => function () use (&$locator) { return $locator->get('bar'); }, ]); @@ -77,12 +77,10 @@ class ServiceLocatorTest extends TestCase $locator->get('foo'); } - /** - * @expectedException \Psr\Container\ContainerExceptionInterface - * @expectedExceptionMessage Circular reference detected for service "bar", path: "bar -> baz -> bar". - */ public function testThrowsOnCircularReference() { + $this->expectException('Psr\Container\ContainerExceptionInterface'); + $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> baz -> bar".'); $locator = $this->getServiceLocator([ 'foo' => function () use (&$locator) { return $locator->get('bar'); }, 'bar' => function () use (&$locator) { return $locator->get('baz'); }, diff --git a/src/Symfony/Contracts/Translation/Test/TranslatorTest.php b/src/Symfony/Contracts/Translation/Test/TranslatorTest.php index 48466300b5..5bfb0f8df6 100644 --- a/src/Symfony/Contracts/Translation/Test/TranslatorTest.php +++ b/src/Symfony/Contracts/Translation/Test/TranslatorTest.php @@ -158,10 +158,10 @@ class TranslatorTest extends TestCase /** * @dataProvider getNonMatchingMessages - * @expectedException \InvalidArgumentException */ public function testThrowExceptionIfMatchingMessageCannotBeFound($id, $number) { + $this->expectException('InvalidArgumentException'); $translator = $this->getTranslator(); $translator->trans($id, ['%count%' => $number]);