minor #32875 [PhpUnitBridge] Remove @expectedException annotation (jderusse)

This PR was squashed before being merged into the 3.4 branch (closes #32875).

Discussion
----------

[PhpUnitBridge] Remove @expectedException annotation

| Q             | A
| ------------- | ---
| Branch?       | 3.4
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #32844
| License       | MIT
| Doc PR        | NA

this PR replaces the deprecated annotation `@expectedException` by calls to the method `expectException`.

To automate the process, I used rector/rector:
```
./vendor/bin/rector process src/Symfony --set phpunit60 -a .phpunit/phpunit-6.5/vendor/autoload.php
```
Which also replace `PHPUnit_Framework_Error_X` by `\PHPUnit\Framework\Error\X`

Commits
-------

a22a9c453f Fix tests
3a626e8778 Fix deprecated phpunit annotation
This commit is contained in:
Nicolas Grekas 2019-08-02 09:38:25 +02:00
commit 8173dafda4
422 changed files with 2573 additions and 4121 deletions

View File

@ -13,17 +13,18 @@ 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\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
class RegisterEventListenersAndSubscribersPassTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
use ForwardCompatTestTrait;
public function testExceptionOnAbstractTaggedSubscriber()
{
$this->expectException('InvalidArgumentException');
$container = $this->createBuilder();
$abstractDefinition = new Definition('stdClass');
@ -35,11 +36,9 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase
$this->process($container);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testExceptionOnAbstractTaggedListener()
{
$this->expectException('InvalidArgumentException');
$container = $this->createBuilder();
$abstractDefinition = new Definition('stdClass');

View File

@ -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',

View File

@ -52,11 +52,9 @@ class DoctrineExtensionTest extends TestCase
});
}
/**
* @expectedException \LogicException
*/
public function testFixManagersAutoMappingsWithTwoAutomappings()
{
$this->expectException('LogicException');
$emConfigs = [
'em1' => [
'auto_mapping' => true,
@ -241,12 +239,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 = [

View File

@ -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');
}

View File

@ -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,

View File

@ -83,12 +83,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('\Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$provider = new EntityUserProvider(

View File

@ -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'],

View File

@ -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();
}

View File

@ -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);
@ -74,11 +72,11 @@ class LintCommandTest extends TestCase
/**
* @group legacy
* @expectedDeprecation Passing a command name as the first argument of "Symfony\Bridge\Twig\Command\LintCommand::__construct()" is deprecated since Symfony 3.4 and support for it will be removed in 4.0. If the command was registered by convention, make it a service instead.
* @expectedException \RuntimeException
* @expectedExceptionMessage The Twig environment needs to be set.
*/
public function testLegacyLintCommand()
{
$this->expectException('RuntimeException');
$this->expectExceptionMessage('The Twig environment needs to be set.');
$command = new LintCommand();
$application = new Application();

View File

@ -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);

View File

@ -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" %}', []);
}

View File

@ -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,30 +48,24 @@ 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();
}
/**
* @expectedException \Twig\Error\SyntaxError
* @expectedExceptionMessage A message inside a transchoice tag must be a simple text in "index" at line 2.
*/
public function testTransChoiceComplexBody()
{
$this->expectException('Twig\Error\SyntaxError');
$this->expectExceptionMessage('A message inside a transchoice tag must be a simple text in "index" at line 2.');
$output = $this->getTemplate("{% transchoice count %}\n{{ 1 + 2 }}{% endtranschoice %}")->render();
}

View File

@ -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;
@ -21,6 +22,8 @@ use Twig\Loader\ArrayLoader;
class TwigExtractorTest extends TestCase
{
use ForwardCompatTestTrait;
/**
* @dataProvider getExtractData
*/
@ -76,11 +79,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('Symfony\Component\Translation\TranslatorInterface')->getMock()));

View File

@ -12,6 +12,7 @@
namespace Symfony\Bridge\Twig\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bridge\Twig\TwigEngine;
use Symfony\Component\Templating\TemplateReference;
use Twig\Environment;
@ -19,6 +20,8 @@ use Twig\Loader\ArrayLoader;
class TwigEngineTest extends TestCase
{
use ForwardCompatTestTrait;
public function testExistsWithTemplateInstances()
{
$engine = $this->getTwig();
@ -58,11 +61,9 @@ class TwigEngineTest extends TestCase
$this->assertSame('foo', $engine->render(new TemplateReference('index')));
}
/**
* @expectedException \Twig\Error\SyntaxError
*/
public function testRenderWithError()
{
$this->expectException('Twig\Error\SyntaxError');
$engine = $this->getTwig();
$engine->render(new TemplateReference('error'));

View File

@ -12,6 +12,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Command;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\Command\RouterDebugCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
@ -21,6 +22,8 @@ use Symfony\Component\Routing\RouteCollection;
class RouterDebugCommandTest extends TestCase
{
use ForwardCompatTestTrait;
public function testDebugAllRoutes()
{
$tester = $this->createCommandTester();
@ -39,11 +42,9 @@ class RouterDebugCommandTest extends TestCase
$this->assertContains('Route Name | foo', $tester->getDisplay());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testDebugInvalidRoute()
{
$this->expectException('InvalidArgumentException');
$this->createCommandTester()->execute(['name' => 'test']);
}

View File

@ -97,11 +97,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')

View File

@ -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);

View File

@ -11,6 +11,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\DependencyInjection\Container;
@ -31,6 +32,8 @@ use Symfony\Component\Serializer\SerializerInterface;
abstract class ControllerTraitTest extends TestCase
{
use ForwardCompatTestTrait;
abstract protected function createController();
public function testForward()
@ -87,12 +90,10 @@ abstract class ControllerTraitTest 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());
@ -274,11 +275,9 @@ abstract class ControllerTraitTest 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 */
@ -299,11 +298,9 @@ abstract class ControllerTraitTest 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);

View File

@ -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\Templating\EngineInterface;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
@ -20,6 +21,8 @@ use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
*/
class TemplateControllerTest extends TestCase
{
use ForwardCompatTestTrait;
public function testTwig()
{
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
@ -77,12 +80,10 @@ class TemplateControllerTest extends TestCase
$this->assertEquals('bar', $controller->templateAction('mytemplate')->getContent());
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage You can not use the TemplateController if the Templating Component or the Twig Bundle are not available.
*/
public function testNoTwigNorTemplating()
{
$this->expectException('LogicException');
$this->expectExceptionMessage('You can not use the TemplateController if the Templating Component or the Twig Bundle are not available.');
$controller = new TemplateController();
$controller->templateAction('mytemplate')->getContent();

View File

@ -12,6 +12,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddConsoleCommandPass;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\DependencyInjection\ContainerBuilder;
@ -22,6 +23,8 @@ use Symfony\Component\DependencyInjection\Definition;
*/
class AddConsoleCommandPassTest extends TestCase
{
use ForwardCompatTestTrait;
/**
* @dataProvider visibilityProvider
*/
@ -63,12 +66,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->addCompilerPass(new AddConsoleCommandPass());
@ -80,12 +81,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->addCompilerPass(new AddConsoleCommandPass());

View File

@ -12,6 +12,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddConstraintValidatorsPass;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
@ -24,6 +25,8 @@ use Symfony\Component\DependencyInjection\ServiceLocator;
*/
class AddConstraintValidatorsPassTest extends TestCase
{
use ForwardCompatTestTrait;
public function testThatConstraintValidatorServicesAreProcessed()
{
$container = new ContainerBuilder();
@ -46,12 +49,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();
$validatorFactory = $container->register('validator.validator_factory')
->addArgument([]);

View File

@ -96,12 +96,10 @@ class CachePoolPassTest extends TestCase
$this->assertSame(3, $cachePool->getArgument(2));
}
/**
* @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.debug', false);
$container->setParameter('kernel.name', 'app');

View File

@ -12,6 +12,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CachePoolPrunerPass;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\PhpFilesAdapter;
@ -21,6 +22,8 @@ use Symfony\Component\DependencyInjection\Reference;
class CachePoolPrunerPassTest extends TestCase
{
use ForwardCompatTestTrait;
public function testCompilerPassReplacesCommandArgument()
{
$container = new ContainerBuilder();
@ -56,12 +59,10 @@ class CachePoolPrunerPassTest extends TestCase
$this->assertCount($aliasesBefore, $container->getAliases());
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Class "Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\NotFound" used for service "pool.not-found" cannot be found.
*/
public function testCompilerPassThrowsOnInvalidDefinitionClass()
{
$this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException');
$this->expectExceptionMessage('Class "Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\NotFound" used for service "pool.not-found" cannot be found.');
$container = new ContainerBuilder();
$container->register('console.command.cache_pool_prune')->addArgument([]);
$container->register('pool.not-found', NotFound::class)->addTag('cache.pool');

View File

@ -12,6 +12,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\FormPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
@ -24,6 +25,8 @@ use Symfony\Component\DependencyInjection\Reference;
*/
class FormPassTest extends TestCase
{
use ForwardCompatTestTrait;
public function testDoNothingIfFormExtensionNotLoaded()
{
$container = new ContainerBuilder();
@ -124,12 +127,10 @@ class FormPassTest extends TestCase
];
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage extended-type attribute, none was configured for the "my.type_extension" service
*/
public function testAddTaggedFormTypeExtensionWithoutExtendedTypeAttribute()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('extended-type attribute, none was configured for the "my.type_extension" service');
$container = new ContainerBuilder();
$container->addCompilerPass(new FormPass());

View File

@ -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:
*
* <tag name="data_collector" template="YourBundle:Collector:templatename" id="your_collector_name" />
*
* @expectedException \InvalidArgumentException
*/
public function testTemplateNoIdThrowsException()
{
$this->expectException('InvalidArgumentException');
$builder = new ContainerBuilder();
$builder->register('profiler', 'ProfilerClass');
$builder->register('my_collector_service')

View File

@ -12,6 +12,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\SerializerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
@ -25,12 +26,12 @@ use Symfony\Component\DependencyInjection\Reference;
*/
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');
@ -38,12 +39,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([])

View File

@ -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);

View File

@ -107,10 +107,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),
@ -163,10 +163,10 @@ class ConfigurationTest extends TestCase
/**
* @group legacy
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testInvalidTypeTrustedProxies()
{
$this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException');
$processor = new Processor();
$configuration = new Configuration(true);
$processor->processConfiguration($configuration, [
@ -179,10 +179,10 @@ class ConfigurationTest extends TestCase
/**
* @group legacy
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testInvalidValueTrustedProxies()
{
$this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException');
$processor = new Processor();
$configuration = new Configuration(true);

View File

@ -12,6 +12,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection;
use Doctrine\Common\Annotations\Annotation;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddAnnotationsCachedReaderPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
@ -47,6 +48,8 @@ use Symfony\Component\Workflow\Registry;
abstract class FrameworkExtensionTest extends TestCase
{
use ForwardCompatTestTrait;
private static $containerCache = [];
abstract protected function loadFromFile(ContainerBuilder $container, $file);
@ -106,12 +109,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');
}
@ -252,39 +253,31 @@ abstract class FrameworkExtensionTest extends TestCase
$container = $this->createContainerFromFile('workflows_without_type');
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
* @expectedExceptionMessage "type" and "service" cannot be used together.
*/
public function testWorkflowCannotHaveBothTypeAndService()
{
$this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException');
$this->expectExceptionMessage('"type" and "service" cannot be used together.');
$this->createContainerFromFile('workflow_with_type_and_service');
}
/**
* @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');
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
* @expectedExceptionMessage "arguments" and "service" cannot be used together.
*/
public function testWorkflowCannotHaveBothArgumentsAndService()
{
$this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException');
$this->expectExceptionMessage('"arguments" and "service" cannot be used together.');
$this->createContainerFromFile('workflow_with_arguments_and_service');
}
@ -430,11 +423,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);
@ -473,11 +464,9 @@ abstract class FrameworkExtensionTest extends TestCase
$this->assertNull($container->getDefinition('session.storage.php_bridge')->getArgument(0));
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testNullSessionHandlerWithSavePath()
{
$this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException');
$this->createContainerFromFile('session_savepath');
}
@ -645,11 +634,9 @@ abstract class FrameworkExtensionTest extends TestCase
$this->assertFalse($container->has('templating.helper.translator'));
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testTemplatingRequiresAtLeastOneEngine()
{
$this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException');
$container = $this->createContainer();
$loader = new FrameworkExtension();
$loader->load([['templating' => null]], $container);

View File

@ -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' => [

View File

@ -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]);
}

View File

@ -11,12 +11,15 @@
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\Exception\InvalidArgumentException;
class CachePoolsTest extends AbstractWebTestCase
{
use ForwardCompatTestTrait;
public function testCachePools()
{
$this->doTestCachePools([], AdapterInterface::class);
@ -34,7 +37,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;
}
@ -59,7 +62,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;
}

View File

@ -12,6 +12,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Routing;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\DependencyInjection\Config\ContainerParametersResource;
use Symfony\Component\Routing\Route;
@ -19,6 +20,8 @@ use Symfony\Component\Routing\RouteCollection;
class RouterTest extends TestCase
{
use ForwardCompatTestTrait;
public function testGenerateWithServiceParam()
{
$routes = new RouteCollection();
@ -133,12 +136,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)%'));
@ -168,12 +169,10 @@ class RouterTest extends TestCase
);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException
* @expectedExceptionMessage You have requested a non-existent parameter "nope".
*/
public function testExceptionOnNonExistentParameter()
{
$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%'));
@ -184,12 +183,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%'));

View File

@ -12,11 +12,14 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Templating;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\Templating\DelegatingEngine;
use Symfony\Component\HttpFoundation\Response;
class DelegatingEngineTest extends TestCase
{
use ForwardCompatTestTrait;
public function testSupportsRetrievesEngineFromTheContainer()
{
$container = $this->getContainerMock([
@ -43,12 +46,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);
$container = $this->getContainerMock([

View File

@ -11,12 +11,15 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Templating\Loader;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\Templating\Loader\TemplateLocator;
use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
class TemplateLocatorTest extends TestCase
{
use ForwardCompatTestTrait;
public function testLocateATemplate()
{
$template = new TemplateReference('bundle', 'controller', 'name', 'format', 'engine');
@ -77,11 +80,9 @@ class TemplateLocatorTest extends TestCase
}
}
/**
* @expectedException \InvalidArgumentException
*/
public function testThrowsAnExceptionWhenTemplateIsNotATemplateReferenceInterface()
{
$this->expectException('InvalidArgumentException');
$locator = new TemplateLocator($this->getFileLocator());
$locator->locate('template');
}

View File

@ -11,6 +11,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Templating;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables;
use Symfony\Bundle\FrameworkBundle\Templating\PhpEngine;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
@ -23,6 +24,8 @@ use Symfony\Component\Templating\TemplateNameParser;
class PhpEngineTest extends TestCase
{
use ForwardCompatTestTrait;
public function testEvaluateAddsAppGlobal()
{
$container = $this->getContainer();
@ -43,11 +46,9 @@ class PhpEngineTest extends TestCase
$this->assertEmpty($globals['app']->getRequest());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testGetInvalidHelper()
{
$this->expectException('InvalidArgumentException');
$container = $this->getContainer();
$loader = $this->getMockForAbstractClass('Symfony\Component\Templating\Loader\Loader');
$engine = new PhpEngine(new TemplateNameParser(), $container, $loader);

View File

@ -77,11 +77,9 @@ class TemplateNameParserTest extends TestCase
];
}
/**
* @expectedException \InvalidArgumentException
*/
public function testParseValidNameWithNotFoundBundle()
{
$this->expectException('InvalidArgumentException');
$this->parser->parse('BarBundle:Post:index.html.php');
}

View File

@ -110,10 +110,10 @@ class TranslatorTest extends TestCase
/**
* @group legacy
* @expectedDeprecation The "Symfony\Bundle\FrameworkBundle\Translation\Translator::__construct()" method takes the default locale as the 3rd argument since Symfony 3.3. Not passing it is deprecated and will trigger an error in 4.0.
* @expectedException \InvalidArgumentException
*/
public function testTransWithCachingWithInvalidLocaleOmittingLocale()
{
$this->expectException('InvalidArgumentException');
$loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock();
$translator = $this->getTranslator($loader, ['cache_dir' => $this->tmpDir], 'loader', '\Symfony\Bundle\FrameworkBundle\Tests\Translation\TranslatorWithInvalidLocale', null);
@ -159,11 +159,11 @@ class TranslatorTest extends TestCase
/**
* @group legacy
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Missing third $defaultLocale argument.
*/
public function testGetDefaultLocaleOmittingLocaleWithPsrContainer()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Missing third $defaultLocale argument.');
$container = $this->getMockBuilder(ContainerInterface::class)->getMock();
$translator = new Translator($container, new MessageFormatter());
}
@ -250,12 +250,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');
@ -285,12 +283,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']));

View File

@ -12,6 +12,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Validator;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\Validator\ConstraintValidatorFactory;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\Validator\Constraint;
@ -23,6 +24,8 @@ use Symfony\Component\Validator\ConstraintValidator;
*/
class ConstraintValidatorFactoryTest extends TestCase
{
use ForwardCompatTestTrait;
public function testGetInstanceCreatesValidator()
{
$factory = new ConstraintValidatorFactory(new Container());
@ -59,11 +62,9 @@ class ConstraintValidatorFactoryTest extends TestCase
$this->assertSame($validator, $factory->getInstance(new ConstraintAliasStub()));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ValidatorException
*/
public function testGetInstanceInvalidValidatorClass()
{
$this->expectException('Symfony\Component\Validator\Exception\ValidatorException');
$constraint = $this->getMockBuilder('Symfony\\Component\\Validator\\Constraint')->getMock();
$constraint
->expects($this->exactly(2))

View File

@ -24,11 +24,9 @@ class AddSecurityVotersPassTest extends TestCase
{
use ForwardCompatTestTrait;
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException
*/
public function testNoVoters()
{
$this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException');
$container = new ContainerBuilder();
$container
->register('security.access.decision_manager', AccessDecisionManager::class)

View File

@ -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\Argon2iPasswordEncoder;
abstract class CompleteConfigurationTest extends TestCase
{
use ForwardCompatTestTrait;
abstract protected function getLoader(ContainerBuilder $container);
abstract protected function getFileExtension();
@ -553,12 +556,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');
}
@ -573,21 +574,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');
}

View File

@ -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.
@ -33,11 +36,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' => [],
@ -49,11 +50,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' => [

View File

@ -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'],

View File

@ -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\Bundle\SecurityBundle\Tests\DependencyInjection\Fixtures\UserProvider\DummyProvider;
@ -19,12 +20,12 @@ use Symfony\Component\DependencyInjection\ContainerBuilder;
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', [
@ -46,12 +47,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', [
@ -70,12 +69,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');
@ -186,11 +183,11 @@ class SecurityExtensionTest extends TestCase
/**
* @group legacy
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
* @expectedExceptionMessage Firewalls "some_firewall" and "some_other_firewall" need to have the same value for option "logout_on_user_change" as they are sharing the context "my_context"
*/
public function testThrowsIfLogoutOnUserChangeDifferentForSharedContext()
{
$this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException');
$this->expectExceptionMessage('Firewalls "some_firewall" and "some_other_firewall" need to have the same value for option "logout_on_user_change" as they are sharing the context "my_context"');
$container = $this->getRawContainer();
$container->loadFromExtension('security', [

View File

@ -208,12 +208,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(), []));

View File

@ -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);
}
}

View File

@ -11,12 +11,15 @@
namespace Symfony\Bundle\TwigBundle\Tests\Loader;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference;
use Symfony\Bundle\TwigBundle\Loader\FilesystemLoader;
use Symfony\Bundle\TwigBundle\Tests\TestCase;
class FilesystemLoaderTest extends TestCase
{
use ForwardCompatTestTrait;
public function testGetSourceContext()
{
$parser = $this->getMockBuilder('Symfony\Component\Templating\TemplateNameParserInterface')->getMock();
@ -51,11 +54,9 @@ class FilesystemLoaderTest extends TestCase
$this->assertTrue($loader->exists($template));
}
/**
* @expectedException \Twig\Error\LoaderError
*/
public function testTwigErrorIfLocatorThrowsInvalid()
{
$this->expectException('Twig\Error\LoaderError');
$parser = $this->getMockBuilder('Symfony\Component\Templating\TemplateNameParserInterface')->getMock();
$parser
->expects($this->once())
@ -75,11 +76,9 @@ class FilesystemLoaderTest extends TestCase
$loader->getCacheKey('name.format.engine');
}
/**
* @expectedException \Twig\Error\LoaderError
*/
public function testTwigErrorIfLocatorReturnsFalse()
{
$this->expectException('Twig\Error\LoaderError');
$parser = $this->getMockBuilder('Symfony\Component\Templating\TemplateNameParserInterface')->getMock();
$parser
->expects($this->once())
@ -99,12 +98,10 @@ class FilesystemLoaderTest extends TestCase
$loader->getCacheKey('name.format.engine');
}
/**
* @expectedException \Twig\Error\LoaderError
* @expectedExceptionMessageRegExp /Unable to find template "name\.format\.engine" \(looked into: .*Tests.Loader.\.\..DependencyInjection.Fixtures.Resources.views\)/
*/
public function testTwigErrorIfTemplateDoesNotExist()
{
$this->expectException('Twig\Error\LoaderError');
$this->expectExceptionMessageRegExp('/Unable to find template "name\.format\.engine" \(looked into: .*Tests.Loader.\.\..DependencyInjection.Fixtures.Resources.views\)/');
$parser = $this->getMockBuilder('Symfony\Component\Templating\TemplateNameParserInterface')->getMock();
$locator = $this->getMockBuilder('Symfony\Component\Config\FileLocatorInterface')->getMock();

View File

@ -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');
}

View File

@ -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');
}

View File

@ -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
*/
@ -88,19 +91,15 @@ 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());
}
/**
* @expectedException \Symfony\Component\Asset\Exception\InvalidArgumentException
*/
public function testWrongBaseUrl()
{
$this->expectException('Symfony\Component\Asset\Exception\InvalidArgumentException');
new UrlPackage(['not-a-url'], new EmptyVersionStrategy());
}

View File

@ -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');
}

View File

@ -197,12 +197,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');
}
}

View File

@ -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,26 +25,24 @@ use Symfony\Component\Cache\Tests\Fixtures\ExternalAdapter;
*/
class ChainAdapterTest extends AdapterTestCase
{
use ForwardCompatTestTrait;
public function createCachePool($defaultLifetime = 0)
{
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()]);
}

View File

@ -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();

View File

@ -66,11 +66,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]);
}
@ -96,12 +96,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');
}

View File

@ -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\ProxyAdapter;
use Symfony\Component\Cache\CacheItem;
@ -21,6 +22,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.',
@ -32,12 +35,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));

View File

@ -58,11 +58,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);
}
@ -77,11 +77,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);
}

View File

@ -33,11 +33,9 @@ class TagAwareAdapterTest extends AdapterTestCase
FilesystemAdapterTest::rmdir(sys_get_temp_dir().'/symfony-cache');
}
/**
* @expectedException \Psr\Cache\InvalidArgumentException
*/
public function testInvalidTag()
{
$this->expectException('Psr\Cache\InvalidArgumentException');
$pool = $this->createCachePool();
$item = $pool->getItem('foo');
$item->tag(':');

View File

@ -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);
}
@ -66,11 +69,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();
$item->tag($tag);
}

View File

@ -12,6 +12,7 @@
namespace Symfony\Component\Cache\Tests\Simple;
use Psr\SimpleCache\CacheInterface;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Component\Cache\Simple\ArrayCache;
use Symfony\Component\Cache\Simple\ChainCache;
@ -22,26 +23,24 @@ use Symfony\Component\Cache\Simple\FilesystemCache;
*/
class ChainCacheTest extends CacheTestCase
{
use ForwardCompatTestTrait;
public function createSimpleCache($defaultLifetime = 0)
{
return new ChainCache([new ArrayCache($defaultLifetime), new FilesystemCache('', $defaultLifetime)], $defaultLifetime);
}
/**
* @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException
* @expectedExceptionMessage At least one cache must be specified.
*/
public function testEmptyCachesException()
{
$this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
$this->expectExceptionMessage('At least one cache must be specified.');
new ChainCache([]);
}
/**
* @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException
* @expectedExceptionMessage The class "stdClass" does not implement
*/
public function testInvalidCacheException()
{
$this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
$this->expectExceptionMessage('The class "stdClass" does not implement');
new ChainCache([new \stdClass()]);
}

View File

@ -76,11 +76,11 @@ class MemcachedCacheTest extends CacheTestCase
/**
* @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::');
MemcachedCache::createConnection([], [$name => $value]);
}
@ -105,12 +105,10 @@ class MemcachedCacheTest extends CacheTestCase
$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');
}

View File

@ -48,11 +48,11 @@ class RedisCacheTest extends AbstractRedisCacheTest
/**
* @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');
RedisCache::createConnection($dsn);
}
@ -67,11 +67,11 @@ class RedisCacheTest extends AbstractRedisCacheTest
/**
* @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');
RedisCache::createConnection($dsn);
}

View File

@ -12,6 +12,7 @@
namespace Symfony\Component\ClassLoader\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Component\ClassLoader\ClassCollectionLoader;
use Symfony\Component\ClassLoader\Tests\Fixtures\DeclaredClass;
use Symfony\Component\ClassLoader\Tests\Fixtures\WarmedClass;
@ -26,6 +27,8 @@ require_once __DIR__.'/Fixtures/ClassesWithParents/A.php';
*/
class ClassCollectionLoaderTest extends TestCase
{
use ForwardCompatTestTrait;
public function testTraitDependencies()
{
require_once __DIR__.'/Fixtures/deps/traits.php';
@ -208,11 +211,9 @@ class ClassCollectionLoaderTest extends TestCase
];
}
/**
* @expectedException \InvalidArgumentException
*/
public function testUnableToLoadClassException()
{
$this->expectException('InvalidArgumentException');
if (is_file($file = sys_get_temp_dir().'/foo.php')) {
unlink($file);
}

View File

@ -12,16 +12,17 @@
namespace Symfony\Component\Config\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Component\Config\ConfigCacheFactory;
class ConfigCacheFactoryTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Invalid type for callback argument. Expected callable, but got "object".
*/
use ForwardCompatTestTrait;
public function testCacheWithInvalidCallback()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Invalid type for callback argument. Expected callable, but got "object".');
$cacheFactory = new ConfigCacheFactory(true);
$cacheFactory->cache('file', new \stdClass());

View File

@ -21,21 +21,17 @@ 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']);
}
@ -179,24 +175,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');
@ -206,12 +198,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();
}

View File

@ -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);
}

View File

@ -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\ScalarNodeDefinition;
use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;
@ -19,6 +20,8 @@ use Symfony\Component\Config\Definition\Processor;
class ArrayNodeDefinitionTest extends TestCase
{
use ForwardCompatTestTrait;
public function testAppendingSomeNode()
{
$parent = new ArrayNodeDefinition('root');
@ -36,11 +39,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');
\call_user_func_array([$node, $method], $args);
@ -58,11 +61,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()
@ -71,11 +72,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([])

View File

@ -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();
}

View File

@ -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([]);
}

View File

@ -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();

View File

@ -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')

View File

@ -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();
}

View File

@ -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, []);
}
@ -43,12 +44,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');
}

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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();
$tree = $tb
->root('root', 'array')
@ -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();
$tree = $tb
->root('config', 'array')

View File

@ -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'],

View File

@ -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);

View File

@ -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(null, __DIR__);

View File

@ -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\FileLoaderLoadException
*/
public function testLoadThrowsAnExceptionIfTheResourceCannotBeLoaded()
{
$this->expectException('Symfony\Component\Config\Exception\FileLoaderLoadException');
$loader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock();
$loader->expects($this->once())->method('supports')->willReturn(false);
$resolver = new LoaderResolver([$loader]);

View File

@ -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\FileLoaderLoadException
*/
public function testResolveWhenResolverCannotFindLoader()
{
$this->expectException('Symfony\Component\Config\Exception\FileLoaderLoadException');
$resolver = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderResolverInterface')->getMock();
$resolver->expects($this->once())
->method('resolve')

View File

@ -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.');
}

View File

@ -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));
}

View File

@ -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));
}

View File

@ -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();

View File

@ -201,12 +201,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());
}
@ -269,12 +267,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');
}
@ -328,22 +324,18 @@ class ApplicationTest extends TestCase
$this->assertEquals('test-ambiguous', $application->find('test')->getName());
}
/**
* @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException
* @expectedExceptionMessage There are no commands defined in the "bar" namespace.
*/
public function testFindInvalidNamespace()
{
$this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException');
$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());
@ -386,12 +378,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());
@ -479,12 +469,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);
@ -660,12 +650,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());
@ -1035,12 +1023,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);
@ -1063,11 +1049,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);
@ -1216,12 +1202,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);
@ -1396,11 +1380,11 @@ class ApplicationTest extends TestCase
/**
* @requires PHP 7
* @expectedException \LogicException
* @expectedExceptionMessage error
*/
public function testRunWithErrorAndDispatcher()
{
$this->expectException('LogicException');
$this->expectExceptionMessage('error');
$application = new Application();
$application->setDispatcher($this->getDispatcher());
$application->setAutoExit(false);
@ -1650,11 +1634,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');

View File

@ -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());
}
@ -217,12 +215,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');
}
@ -290,22 +286,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]);

View File

@ -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');
}

View File

@ -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');
}

View File

@ -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
*/
@ -121,12 +124,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);
@ -139,12 +140,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);
@ -227,12 +226,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);

View File

@ -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'));

View File

@ -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');
}

View File

@ -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();
@ -518,12 +521,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',
@ -748,7 +749,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
}
/**
* @group legacy
* @group legacy
* @dataProvider getAskConfirmationData
*/
public function testLegacyAskConfirmation($question, $expected, $default = true)
@ -810,7 +811,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
}
/**
* @group legacy
* @group legacy
* @dataProvider simpleAnswerProvider
*/
public function testLegacySelectChoiceFromSimpleChoices($providedAnswer, $expectedValue)
@ -834,7 +835,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
}
/**
* @group legacy
* @group legacy
* @dataProvider mixedKeysChoiceListAnswerProvider
*/
public function testLegacyChoiceFromChoicelistWithMixedKeys($providedAnswer, $expectedValue)
@ -859,7 +860,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
}
/**
* @group legacy
* @group legacy
* @dataProvider answerProvider
*/
public function testLegacySelectChoiceFromChoiceList($providedAnswer, $expectedValue)
@ -883,12 +884,12 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
}
/**
* @group legacy
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The provided answer is ambiguous. Value should be one of env_2 or env_3.
* @group legacy
*/
public function testLegacyAmbiguousChoiceFromChoicelist()
{
$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',
@ -938,32 +939,26 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
$dialog->ask($this->createInputInterfaceMock(), $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?');
@ -976,12 +971,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');
}

View File

@ -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?'));
}

View File

@ -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('TEST');
}

View File

@ -729,12 +729,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'])
@ -808,22 +806,18 @@ TABLE;
$this->assertEquals($expected, $this->getOutputContent($output));
}
/**
* @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');
}

View File

@ -94,22 +94,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');
}

View File

@ -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]);

View File

@ -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);
}
@ -95,27 +93,21 @@ class InputOptionTest extends TestCase
];
}
/**
* @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', '-');
}
@ -164,22 +156,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');
}

View File

@ -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();

Some files were not shown because too many files have changed in this diff Show More