Issue #2927806 by alexpott, mondrake, jibran, Mile23: Use PHPUnit 6 for testing when PHP version >= 7.2

8.5.x
Nathaniel Catchpole 2017-12-22 12:47:46 +00:00
parent 4e5b4b09bd
commit 03fd77c842
57 changed files with 485 additions and 131 deletions

View File

@ -49,11 +49,11 @@
}, },
"scripts": { "scripts": {
"pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump", "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
"post-autoload-dump": [ "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
"Drupal\\Core\\Composer\\Composer::ensureHtaccess"
],
"post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup", "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
"post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup", "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
"post-install-cmd": "Drupal\\Core\\Composer\\Composer::upgradePHPUnit",
"drupal-phpunit-upgrade": "@composer update phpunit/phpunit --with-dependencies --no-progress",
"phpcs": "phpcs --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --", "phpcs": "phpcs --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --",
"phpcbf": "phpcbf --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --" "phpcbf": "phpcbf --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --"
}, },

View File

@ -44,7 +44,7 @@
"jcalderonzumba/gastonjs": "^1.0.2", "jcalderonzumba/gastonjs": "^1.0.2",
"jcalderonzumba/mink-phantomjs-driver": "^0.3.1", "jcalderonzumba/mink-phantomjs-driver": "^0.3.1",
"mikey179/vfsStream": "^1.2", "mikey179/vfsStream": "^1.2",
"phpunit/phpunit": ">=4.8.35 <5", "phpunit/phpunit": "^4.8.35 || ^6.1",
"phpspec/prophecy": "^1.4", "phpspec/prophecy": "^1.4",
"symfony/css-selector": "~3.2.8", "symfony/css-selector": "~3.2.8",
"symfony/phpunit-bridge": "^3.4.0@beta" "symfony/phpunit-bridge": "^3.4.0@beta"

View File

@ -143,6 +143,32 @@ EOT;
} }
} }
/**
* Fires the drupal-phpunit-upgrade script event if necessary.
*
* @param \Composer\Script\Event $event
*/
public static function upgradePHPUnit(Event $event) {
$repository = $event->getComposer()->getRepositoryManager()->getLocalRepository();
// This is, essentially, a null constraint. We only care whether the package
// is present in the vendor directory yet, but findPackage() requires it.
$constraint = new Constraint('>', '');
$phpunit_package = $repository->findPackage('phpunit/phpunit', $constraint);
if (!$phpunit_package) {
// There is nothing to do. The user is probably installing using the
// --no-dev flag.
return;
}
// If the PHP version is 7.2 or above and PHPUnit is less than version 6
// call the drupal-phpunit-upgrade script to upgrade PHPUnit.
if (version_compare(PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION, '7.2') >= 0 && version_compare($phpunit_package->getVersion(), '6.1') < 0) {
$event->getComposer()
->getEventDispatcher()
->dispatchScript('drupal-phpunit-upgrade');
}
}
/** /**
* Remove possibly problematic test files from vendored projects. * Remove possibly problematic test files from vendored projects.
* *

View File

@ -49,6 +49,7 @@ class BlockPageVariantTest extends UnitTestCase {
$container = new Container(); $container = new Container();
$cache_context_manager = $this->getMockBuilder('Drupal\Core\Cache\CacheContextsManager') $cache_context_manager = $this->getMockBuilder('Drupal\Core\Cache\CacheContextsManager')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(['assertValidTokens'])
->getMock(); ->getMock();
$container->set('cache_contexts_manager', $cache_context_manager); $container->set('cache_contexts_manager', $cache_context_manager);
$cache_context_manager->expects($this->any()) $cache_context_manager->expects($this->any())
@ -209,9 +210,6 @@ class BlockPageVariantTest extends UnitTestCase {
$title_block_plugin = $this->getMock('Drupal\Core\Block\TitleBlockPluginInterface'); $title_block_plugin = $this->getMock('Drupal\Core\Block\TitleBlockPluginInterface');
foreach ($blocks_config as $block_id => $block_config) { foreach ($blocks_config as $block_id => $block_config) {
$block = $this->getMock('Drupal\block\BlockInterface'); $block = $this->getMock('Drupal\block\BlockInterface');
$block->expects($this->any())
->method('getContexts')
->willReturn([]);
$block->expects($this->atLeastOnce()) $block->expects($this->atLeastOnce())
->method('getPlugin') ->method('getPlugin')
->willReturn($block_config[1] ? $main_content_block_plugin : ($block_config[2] ? $messages_block_plugin : ($block_config[3] ? $title_block_plugin : $block_plugin))); ->willReturn($block_config[1] ? $main_content_block_plugin : ($block_config[2] ? $messages_block_plugin : ($block_config[3] ? $title_block_plugin : $block_plugin)));

View File

@ -269,7 +269,7 @@ class CommentLinkBuilderTest extends UnitTestCase {
*/ */
protected function getMockNode($has_field, $comment_status, $form_location, $comment_count) { protected function getMockNode($has_field, $comment_status, $form_location, $comment_count) {
$node = $this->getMock('\Drupal\node\NodeInterface'); $node = $this->getMock('\Drupal\node\NodeInterface');
$node->expects($this->once()) $node->expects($this->any())
->method('hasField') ->method('hasField')
->willReturn($has_field); ->willReturn($has_field);

View File

@ -367,7 +367,7 @@ class MailHandlerTest extends UnitTestCase {
$recipient->expects($this->once()) $recipient->expects($this->once())
->method('getEmail') ->method('getEmail')
->willReturn('user2@drupal.org'); ->willReturn('user2@drupal.org');
$recipient->expects($this->once()) $recipient->expects($this->any())
->method('getDisplayName') ->method('getDisplayName')
->willReturn('user2'); ->willReturn('user2');
$recipient->expects($this->once()) $recipient->expects($this->once())

View File

@ -217,7 +217,7 @@ class EntityStateChangeValidationTest extends KernelTestBase {
/** /**
* Tests that content without prior moderation information can be moderated. * Tests that content without prior moderation information can be moderated.
*/ */
public function testLegacyContent() { public function testExistingContentWithNoModeration() {
$node_type = NodeType::create([ $node_type = NodeType::create([
'type' => 'example', 'type' => 'example',
]); ]);
@ -251,7 +251,7 @@ class EntityStateChangeValidationTest extends KernelTestBase {
/** /**
* Tests that content without prior moderation information can be translated. * Tests that content without prior moderation information can be translated.
*/ */
public function testLegacyMultilingualContent() { public function testExistingMultilingualContentWithNoModeration() {
// Enable French. // Enable French.
ConfigurableLanguage::createFromLangcode('fr')->save(); ConfigurableLanguage::createFromLangcode('fr')->save();

View File

@ -20,6 +20,7 @@ class CckFileTest extends MigrateDrupalTestBase {
* Tests configurability of file migration name. * Tests configurability of file migration name.
* *
* @covers ::__construct * @covers ::__construct
* @expectedDeprecation CckFile is deprecated in Drupal 8.3.x and will be be removed before Drupal 9.0.x. Use \Drupal\file\Plugin\migrate\process\d6\FieldFile instead.
*/ */
public function testConfigurableFileMigration() { public function testConfigurableFileMigration() {
$migration = Migration::create($this->container, [], 'custom_migration', []); $migration = Migration::create($this->container, [], 'custom_migration', []);

View File

@ -17,6 +17,8 @@ class CckFileTest extends UnitTestCase {
/** /**
* Tests that alt and title attributes are included in transformed values. * Tests that alt and title attributes are included in transformed values.
*
* @expectedDeprecation CckFile is deprecated in Drupal 8.3.x and will be be removed before Drupal 9.0.x. Use \Drupal\file\Plugin\migrate\process\d6\FieldFile instead.
*/ */
public function testTransformAltTitle() { public function testTransformAltTitle() {
$executable = $this->prophesize(MigrateExecutableInterface::class)->reveal(); $executable = $this->prophesize(MigrateExecutableInterface::class)->reveal();

View File

@ -53,6 +53,8 @@ class LinkCckTest extends KernelTestBase {
/** /**
* @covers ::processCckFieldValues * @covers ::processCckFieldValues
* @expectedDeprecation CckFieldPluginBase is deprecated in Drupal 8.3.x and will be be removed before Drupal 9.0.x. Use \Drupal\migrate_drupal\Plugin\migrate\field\FieldPluginBase instead.
* @expectedDeprecation MigrateCckFieldInterface is deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.x. Use \Drupal\migrate_drupal\Annotation\MigrateField instead.
*/ */
public function testProcessCckFieldValues() { public function testProcessCckFieldValues() {
$this->plugin->processFieldInstance($this->migration); $this->plugin->processFieldInstance($this->migration);

View File

@ -46,6 +46,8 @@ class LinkCckTest extends UnitTestCase {
/** /**
* @covers ::processCckFieldValues * @covers ::processCckFieldValues
* @expectedDeprecation CckFieldPluginBase is deprecated in Drupal 8.3.x and will be be removed before Drupal 9.0.x. Use \Drupal\migrate_drupal\Plugin\migrate\field\FieldPluginBase instead.
* @expectedDeprecation MigrateCckFieldInterface is deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.x. Use \Drupal\migrate_drupal\Annotation\MigrateField instead.
*/ */
public function testProcessCckFieldValues() { public function testProcessCckFieldValues() {
$this->plugin->processCckFieldValues($this->migration, 'somefieldname', []); $this->plugin->processCckFieldValues($this->migration, 'somefieldname', []);

View File

@ -9,7 +9,6 @@ use Drupal\migrate\Plugin\migrate\process\Download;
use Drupal\migrate\MigrateExecutableInterface; use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row; use Drupal\migrate\Row;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
/** /**
* Tests the download process plugin. * Tests the download process plugin.
@ -100,14 +99,8 @@ class DownloadTest extends FileTestBase {
* The local URI of the downloaded file. * The local URI of the downloaded file.
*/ */
protected function doTransform($destination_uri, $configuration = []) { protected function doTransform($destination_uri, $configuration = []) {
// The HTTP client will return a file with contents 'It worked!'
$body = fopen('data://text/plain;base64,SXQgd29ya2VkIQ==', 'r');
// Prepare a mock HTTP client. // Prepare a mock HTTP client.
$this->container->set('http_client', $this->getMock(Client::class)); $this->container->set('http_client', $this->getMock(Client::class));
$this->container->get('http_client')
->method('get')
->willReturn(new Response(200, [], $body));
// Instantiate the plugin statically so it can pull dependencies out of // Instantiate the plugin statically so it can pull dependencies out of
// the container. // the container.

View File

@ -78,11 +78,6 @@ abstract class MigrateTestCase extends UnitTestCase {
$configuration = &$this->migrationConfiguration; $configuration = &$this->migrationConfiguration;
$migration->method('getHighWaterProperty')
->willReturnCallback(function () use ($configuration) {
return isset($configuration['high_water_property']) ? $configuration['high_water_property'] : '';
});
$migration->method('set') $migration->method('set')
->willReturnCallback(function ($argument, $value) use (&$configuration) { ->willReturnCallback(function ($argument, $value) use (&$configuration) {
$configuration[$argument] = $value; $configuration[$argument] = $value;

View File

@ -134,8 +134,6 @@ class PathBasedBreadcrumbBuilderTest extends UnitTestCase {
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$cache_contexts_manager->method('assertValidTokens')->willReturn(TRUE); $cache_contexts_manager->method('assertValidTokens')->willReturn(TRUE);
$cache_contexts_manager->expects($this->any())
->method('validate_tokens');
$container = new Container(); $container = new Container();
$container->set('cache_contexts_manager', $cache_contexts_manager); $container->set('cache_contexts_manager', $cache_contexts_manager);
\Drupal::setContainer($container); \Drupal::setContainer($container);

View File

@ -11,7 +11,7 @@ use Drupal\taxonomy\Entity\Vocabulary;
* *
* @group taxonomy * @group taxonomy
*/ */
class LegacyTest extends TaxonomyTestBase { class EarlyDateTest extends TaxonomyTestBase {
/** /**
* Modules to enable. * Modules to enable.
@ -51,7 +51,7 @@ class LegacyTest extends TaxonomyTestBase {
/** /**
* Test taxonomy functionality with nodes prior to 1970. * Test taxonomy functionality with nodes prior to 1970.
*/ */
public function testTaxonomyLegacyNode() { public function testTaxonomyEarlyDateNode() {
// Posts an article with a taxonomy term and a date prior to 1970. // Posts an article with a taxonomy term and a date prior to 1970.
$date = new DrupalDateTime('1969-01-01 00:00:00'); $date = new DrupalDateTime('1969-01-01 00:00:00');
$edit = []; $edit = [];

View File

@ -10,7 +10,7 @@ use Drupal\views\Entity\View;
* *
* @group views * @group views
*/ */
class LegacyBulkFormUpdateTest extends UpdatePathTestBase { class BulkFormUpdateTest extends UpdatePathTestBase {
/** /**
* {@inheritdoc} * {@inheritdoc}

View File

@ -70,7 +70,7 @@ class ViewsBlockTest extends UnitTestCase {
$this->executable = $this->getMockBuilder('Drupal\views\ViewExecutable') $this->executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(['buildRenderable', 'setDisplay', 'setItemsPerPage']) ->setMethods(['buildRenderable', 'setDisplay', 'setItemsPerPage', 'getShowAdminLinks'])
->getMock(); ->getMock();
$this->executable->expects($this->any()) $this->executable->expects($this->any())
->method('setDisplay') ->method('setDisplay')

View File

@ -8,8 +8,7 @@
<phpunit bootstrap="tests/bootstrap.php" colors="true" <phpunit bootstrap="tests/bootstrap.php" colors="true"
beStrictAboutTestsThatDoNotTestAnything="true" beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutOutputDuringTests="true" beStrictAboutOutputDuringTests="true"
beStrictAboutChangesToGlobalState="true" beStrictAboutChangesToGlobalState="true">
checkForUnintentionallyCoveredCode="false">
<!-- TODO set printerClass="\Drupal\Tests\Listeners\HtmlOutputPrinter" once <!-- TODO set printerClass="\Drupal\Tests\Listeners\HtmlOutputPrinter" once
https://youtrack.jetbrains.com/issue/WI-24808 is resolved. Drupal provides a https://youtrack.jetbrains.com/issue/WI-24808 is resolved. Drupal provides a
result printer that links to the html output results for functional tests. result printer that links to the html output results for functional tests.
@ -30,7 +29,7 @@
<!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output --> <!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output -->
<env name="BROWSERTEST_OUTPUT_DIRECTORY" value=""/> <env name="BROWSERTEST_OUTPUT_DIRECTORY" value=""/>
<!-- To disable deprecation testing uncomment the next line. --> <!-- To disable deprecation testing uncomment the next line. -->
<!-- <env name="SYMFONY_DEPRECATIONS_HELPER" value="disabled"/> --> <env name="SYMFONY_DEPRECATIONS_HELPER" value="weak_vendors"/>
<!-- Example for changing the driver args to mink tests MINK_DRIVER_ARGS value: '["http://127.0.0.1:8510"]' --> <!-- Example for changing the driver args to mink tests MINK_DRIVER_ARGS value: '["http://127.0.0.1:8510"]' -->
<!-- Example for changing the driver args to phantomjs tests MINK_DRIVER_ARGS_PHANTOMJS value: '["http://127.0.0.1:8510"]' --> <!-- Example for changing the driver args to phantomjs tests MINK_DRIVER_ARGS_PHANTOMJS value: '["http://127.0.0.1:8510"]' -->
</php> </php>

View File

@ -793,7 +793,11 @@ function simpletest_script_run_one_test($test_id, $test_class) {
putenv('SYMFONY_DEPRECATIONS_HELPER=disabled'); putenv('SYMFONY_DEPRECATIONS_HELPER=disabled');
} }
else { else {
putenv('SYMFONY_DEPRECATIONS_HELPER=strict'); // Prevent deprecations caused by vendor code calling deprecated code.
// This also prevents mock objects in PHPUnit 6 triggering silenced
// deprecations from breaking the test suite. We should consider changing
// this to 'strict' once PHPUnit 4 is no longer used.
putenv('SYMFONY_DEPRECATIONS_HELPER=weak_vendors');
} }
if (is_subclass_of($test_class, TestCase::class)) { if (is_subclass_of($test_class, TestCase::class)) {
$status = simpletest_script_run_phpunit($test_id, $test_class); $status = simpletest_script_run_phpunit($test_id, $test_class);

View File

@ -188,7 +188,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
/** /**
* Tests legacy text asserts. * Tests legacy text asserts.
*/ */
public function testLegacyTextAsserts() { public function testTextAsserts() {
$this->drupalGet('test-encoded'); $this->drupalGet('test-encoded');
$dangerous = 'Bad html <script>alert(123);</script>'; $dangerous = 'Bad html <script>alert(123);</script>';
$sanitized = Html::escape($dangerous); $sanitized = Html::escape($dangerous);
@ -202,7 +202,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
/** /**
* Tests legacy field asserts which use xpath directly. * Tests legacy field asserts which use xpath directly.
*/ */
public function testLegacyXpathAsserts() { public function testXpathAsserts() {
$this->drupalGet('test-field-xpath'); $this->drupalGet('test-field-xpath');
$this->assertFieldsByValue($this->xpath("//h1[@class = 'page-title']"), NULL); $this->assertFieldsByValue($this->xpath("//h1[@class = 'page-title']"), NULL);
$this->assertFieldsByValue($this->xpath('//table/tbody/tr[2]/td[1]'), 'one'); $this->assertFieldsByValue($this->xpath('//table/tbody/tr[2]/td[1]'), 'one');
@ -245,7 +245,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
/** /**
* Tests legacy field asserts using textfields. * Tests legacy field asserts using textfields.
*/ */
public function testLegacyFieldAssertsForTextfields() { public function testFieldAssertsForTextfields() {
$this->drupalGet('test-field-xpath'); $this->drupalGet('test-field-xpath');
// *** 1. assertNoField(). // *** 1. assertNoField().
@ -387,7 +387,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
/** /**
* Tests legacy field asserts for options field type. * Tests legacy field asserts for options field type.
*/ */
public function testLegacyFieldAssertsForOptions() { public function testFieldAssertsForOptions() {
$this->drupalGet('test-field-xpath'); $this->drupalGet('test-field-xpath');
// Option field type. // Option field type.
@ -443,7 +443,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
/** /**
* Tests legacy field asserts for button field type. * Tests legacy field asserts for button field type.
*/ */
public function testLegacyFieldAssertsForButton() { public function testFieldAssertsForButton() {
$this->drupalGet('test-field-xpath'); $this->drupalGet('test-field-xpath');
$this->assertFieldById('edit-save', NULL); $this->assertFieldById('edit-save', NULL);
@ -485,7 +485,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
/** /**
* Tests legacy field asserts for checkbox field type. * Tests legacy field asserts for checkbox field type.
*/ */
public function testLegacyFieldAssertsForCheckbox() { public function testFieldAssertsForCheckbox() {
$this->drupalGet('test-field-xpath'); $this->drupalGet('test-field-xpath');
// Part 1 - Test by name. // Part 1 - Test by name.

View File

@ -11,7 +11,7 @@ use Drupal\KernelTests\KernelTestBase;
* @group Messenger * @group Messenger
* @coversDefaultClass \Drupal\Core\Messenger\LegacyMessenger * @coversDefaultClass \Drupal\Core\Messenger\LegacyMessenger
*/ */
class LegacyMessengerTest extends KernelTestBase { class MessengerTest extends KernelTestBase {
/** /**
* Retrieves the Messenger service from LegacyMessenger. * Retrieves the Messenger service from LegacyMessenger.

View File

@ -497,6 +497,11 @@ abstract class BrowserTestBase extends TestCase {
if ($disable_gc) { if ($disable_gc) {
gc_enable(); gc_enable();
} }
// Ensure that the test is not marked as risky because of no assertions. In
// PHPUnit 6 tests that only make assertions using $this->assertSession()
// can be marked as risky.
$this->addToAssertionCount(1);
} }
/** /**

View File

@ -87,7 +87,13 @@ class DateTimePlusTest extends TestCase {
* @dataProvider providerTestInvalidDateDiff * @dataProvider providerTestInvalidDateDiff
*/ */
public function testInvalidDateDiff($input1, $input2, $absolute) { public function testInvalidDateDiff($input1, $input2, $absolute) {
if (method_exists($this, 'expectException')) {
$this->expectException(\BadMethodCallException::class);
$this->expectExceptionMessage('Method Drupal\Component\Datetime\DateTimePlus::diff expects parameter 1 to be a \DateTime or \Drupal\Component\Datetime\DateTimePlus object');
}
else {
$this->setExpectedException(\BadMethodCallException::class, 'Method Drupal\Component\Datetime\DateTimePlus::diff expects parameter 1 to be a \DateTime or \Drupal\Component\Datetime\DateTimePlus object'); $this->setExpectedException(\BadMethodCallException::class, 'Method Drupal\Component\Datetime\DateTimePlus::diff expects parameter 1 to be a \DateTime or \Drupal\Component\Datetime\DateTimePlus object');
}
$interval = $input1->diff($input2, $absolute); $interval = $input1->diff($input2, $absolute);
} }
@ -104,7 +110,12 @@ class DateTimePlusTest extends TestCase {
* @dataProvider providerTestInvalidDateArrays * @dataProvider providerTestInvalidDateArrays
*/ */
public function testInvalidDateArrays($input, $timezone, $class) { public function testInvalidDateArrays($input, $timezone, $class) {
if (method_exists($this, 'expectException')) {
$this->expectException($class);
}
else {
$this->setExpectedException($class); $this->setExpectedException($class);
}
$this->assertInstanceOf( $this->assertInstanceOf(
'\Drupal\Component\DateTimePlus', '\Drupal\Component\DateTimePlus',
DateTimePlus::createFromArray($input, $timezone) DateTimePlus::createFromArray($input, $timezone)
@ -242,7 +253,12 @@ class DateTimePlusTest extends TestCase {
* @dataProvider providerTestInvalidDates * @dataProvider providerTestInvalidDates
*/ */
public function testInvalidDates($input, $timezone, $format, $message, $class) { public function testInvalidDates($input, $timezone, $format, $message, $class) {
if (method_exists($this, 'expectException')) {
$this->expectException($class);
}
else {
$this->setExpectedException($class); $this->setExpectedException($class);
}
DateTimePlus::createFromFormat($format, $input, $timezone); DateTimePlus::createFromFormat($format, $input, $timezone);
} }
@ -800,7 +816,12 @@ class DateTimePlusTest extends TestCase {
// Parse the same date with ['validate_format' => TRUE] and make sure we // Parse the same date with ['validate_format' => TRUE] and make sure we
// get the expected exception. // get the expected exception.
if (method_exists($this, 'expectException')) {
$this->expectException(\UnexpectedValueException::class);
}
else {
$this->setExpectedException(\UnexpectedValueException::class); $this->setExpectedException(\UnexpectedValueException::class);
}
$date = DateTimePlus::createFromFormat('Y-m-d H:i:s', '11-03-31 17:44:00', 'UTC', ['validate_format' => TRUE]); $date = DateTimePlus::createFromFormat('Y-m-d H:i:s', '11-03-31 17:44:00', 'UTC', ['validate_format' => TRUE]);
} }
@ -859,7 +880,13 @@ class DateTimePlusTest extends TestCase {
* @covers ::__call * @covers ::__call
*/ */
public function testChainableNonCallable() { public function testChainableNonCallable() {
if (method_exists($this, 'expectException')) {
$this->expectException(\BadMethodCallException::class);
$this->expectExceptionMessage('Call to undefined method Drupal\Component\Datetime\DateTimePlus::nonexistent()');
}
else {
$this->setExpectedException(\BadMethodCallException::class, 'Call to undefined method Drupal\Component\Datetime\DateTimePlus::nonexistent()'); $this->setExpectedException(\BadMethodCallException::class, 'Call to undefined method Drupal\Component\Datetime\DateTimePlus::nonexistent()');
}
$date = new DateTimePlus('now', 'Australia/Sydney'); $date = new DateTimePlus('now', 'Australia/Sydney');
$date->setTimezone(new \DateTimeZone('America/New_York'))->nonexistent(); $date->setTimezone(new \DateTimeZone('America/New_York'))->nonexistent();
} }

View File

@ -37,8 +37,7 @@ class TimeTest extends TestCase {
protected function setUp() { protected function setUp() {
parent::setUp(); parent::setUp();
$this->requestStack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack'); $this->requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->getMock();
$this->time = new Time($this->requestStack); $this->time = new Time($this->requestStack);
} }

View File

@ -70,7 +70,12 @@ class ContainerTest extends TestCase {
public function testConstruct() { public function testConstruct() {
$container_definition = $this->getMockContainerDefinition(); $container_definition = $this->getMockContainerDefinition();
$container_definition['machine_format'] = !$this->machineFormat; $container_definition['machine_format'] = !$this->machineFormat;
if (method_exists($this, 'expectException')) {
$this->expectException(InvalidArgumentException::class);
}
else {
$this->setExpectedException(InvalidArgumentException::class); $this->setExpectedException(InvalidArgumentException::class);
}
$container = new $this->containerClass($container_definition); $container = new $this->containerClass($container_definition);
} }
@ -93,7 +98,12 @@ class ContainerTest extends TestCase {
* @covers ::getAlternatives * @covers ::getAlternatives
*/ */
public function testGetParameterIfNotFound() { public function testGetParameterIfNotFound() {
if (method_exists($this, 'expectException')) {
$this->expectException(ParameterNotFoundException::class);
}
else {
$this->setExpectedException(ParameterNotFoundException::class); $this->setExpectedException(ParameterNotFoundException::class);
}
$this->container->getParameter('parameter_that_does_not_exist'); $this->container->getParameter('parameter_that_does_not_exist');
} }
@ -103,7 +113,12 @@ class ContainerTest extends TestCase {
* @covers ::getParameter * @covers ::getParameter
*/ */
public function testGetParameterIfNotFoundBecauseNull() { public function testGetParameterIfNotFoundBecauseNull() {
if (method_exists($this, 'expectException')) {
$this->expectException(ParameterNotFoundException::class);
}
else {
$this->setExpectedException(ParameterNotFoundException::class); $this->setExpectedException(ParameterNotFoundException::class);
}
$this->container->getParameter(NULL); $this->container->getParameter(NULL);
} }
@ -137,7 +152,12 @@ class ContainerTest extends TestCase {
*/ */
public function testSetParameterWithFrozenContainer() { public function testSetParameterWithFrozenContainer() {
$this->container = new $this->containerClass($this->containerDefinition); $this->container = new $this->containerClass($this->containerDefinition);
if (method_exists($this, 'expectException')) {
$this->expectException(LogicException::class);
}
else {
$this->setExpectedException(LogicException::class); $this->setExpectedException(LogicException::class);
}
$this->container->setParameter('some_config', 'new_value'); $this->container->setParameter('some_config', 'new_value');
} }
@ -242,7 +262,12 @@ class ContainerTest extends TestCase {
* @covers ::createService * @covers ::createService
*/ */
public function testGetForCircularServices() { public function testGetForCircularServices() {
if (method_exists($this, 'expectException')) {
$this->expectException(ServiceCircularReferenceException::class);
}
else {
$this->setExpectedException(ServiceCircularReferenceException::class); $this->setExpectedException(ServiceCircularReferenceException::class);
}
$this->container->get('circular_dependency'); $this->container->get('circular_dependency');
} }
@ -255,7 +280,12 @@ class ContainerTest extends TestCase {
* @covers ::getServiceAlternatives * @covers ::getServiceAlternatives
*/ */
public function testGetForNonExistantService() { public function testGetForNonExistantService() {
if (method_exists($this, 'expectException')) {
$this->expectException(ServiceNotFoundException::class);
}
else {
$this->setExpectedException(ServiceNotFoundException::class); $this->setExpectedException(ServiceNotFoundException::class);
}
$this->container->get('service_not_exists'); $this->container->get('service_not_exists');
} }
@ -304,7 +334,12 @@ class ContainerTest extends TestCase {
// Reset the service. // Reset the service.
$this->container->set('service_parameter_not_exists', NULL); $this->container->set('service_parameter_not_exists', NULL);
if (method_exists($this, 'expectException')) {
$this->expectException(InvalidArgumentException::class);
}
else {
$this->setExpectedException(InvalidArgumentException::class); $this->setExpectedException(InvalidArgumentException::class);
}
$this->container->get('service_parameter_not_exists'); $this->container->get('service_parameter_not_exists');
} }
@ -316,7 +351,12 @@ class ContainerTest extends TestCase {
* @covers ::resolveServicesAndParameters * @covers ::resolveServicesAndParameters
*/ */
public function testGetForNonExistantParameterDependencyWithException() { public function testGetForNonExistantParameterDependencyWithException() {
if (method_exists($this, 'expectException')) {
$this->expectException(InvalidArgumentException::class);
}
else {
$this->setExpectedException(InvalidArgumentException::class); $this->setExpectedException(InvalidArgumentException::class);
}
$this->container->get('service_parameter_not_exists'); $this->container->get('service_parameter_not_exists');
} }
@ -341,7 +381,12 @@ class ContainerTest extends TestCase {
* @covers ::getAlternatives * @covers ::getAlternatives
*/ */
public function testGetForNonExistantServiceDependencyWithException() { public function testGetForNonExistantServiceDependencyWithException() {
if (method_exists($this, 'expectException')) {
$this->expectException(ServiceNotFoundException::class);
}
else {
$this->setExpectedException(ServiceNotFoundException::class); $this->setExpectedException(ServiceNotFoundException::class);
}
$this->container->get('service_dependency_not_exists'); $this->container->get('service_dependency_not_exists');
} }
@ -361,7 +406,12 @@ class ContainerTest extends TestCase {
* @covers ::createService * @covers ::createService
*/ */
public function testGetForNonExistantNULLService() { public function testGetForNonExistantNULLService() {
if (method_exists($this, 'expectException')) {
$this->expectException(ServiceNotFoundException::class);
}
else {
$this->setExpectedException(ServiceNotFoundException::class); $this->setExpectedException(ServiceNotFoundException::class);
}
$this->container->get(NULL); $this->container->get(NULL);
} }
@ -387,7 +437,12 @@ class ContainerTest extends TestCase {
*/ */
public function testGetForNonExistantServiceWithExceptionOnSecondCall() { public function testGetForNonExistantServiceWithExceptionOnSecondCall() {
$this->assertNull($this->container->get('service_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE), 'Not found service does nto throw exception.'); $this->assertNull($this->container->get('service_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE), 'Not found service does nto throw exception.');
if (method_exists($this, 'expectException')) {
$this->expectException(ServiceNotFoundException::class);
}
else {
$this->setExpectedException(ServiceNotFoundException::class); $this->setExpectedException(ServiceNotFoundException::class);
}
$this->container->get('service_not_exists'); $this->container->get('service_not_exists');
} }
@ -423,7 +478,12 @@ class ContainerTest extends TestCase {
* @covers ::createService * @covers ::createService
*/ */
public function testGetForSyntheticServiceWithException() { public function testGetForSyntheticServiceWithException() {
if (method_exists($this, 'expectException')) {
$this->expectException(RuntimeException::class);
}
else {
$this->setExpectedException(RuntimeException::class); $this->setExpectedException(RuntimeException::class);
}
$this->container->get('synthetic'); $this->container->get('synthetic');
} }
@ -462,7 +522,12 @@ class ContainerTest extends TestCase {
* @covers ::createService * @covers ::createService
*/ */
public function testGetForWrongFactory() { public function testGetForWrongFactory() {
if (method_exists($this, 'expectException')) {
$this->expectException(RuntimeException::class);
}
else {
$this->setExpectedException(RuntimeException::class); $this->setExpectedException(RuntimeException::class);
}
$this->container->get('wrong_factory'); $this->container->get('wrong_factory');
} }
@ -500,7 +565,12 @@ class ContainerTest extends TestCase {
* @covers ::createService * @covers ::createService
*/ */
public function testGetForConfiguratorWithException() { public function testGetForConfiguratorWithException() {
if (method_exists($this, 'expectException')) {
$this->expectException(InvalidArgumentException::class);
}
else {
$this->setExpectedException(InvalidArgumentException::class); $this->setExpectedException(InvalidArgumentException::class);
}
$this->container->get('configurable_service_exception'); $this->container->get('configurable_service_exception');
} }
@ -598,7 +668,12 @@ class ContainerTest extends TestCase {
* @covers ::resolveServicesAndParameters * @covers ::resolveServicesAndParameters
*/ */
public function testResolveServicesAndParametersForInvalidArgument() { public function testResolveServicesAndParametersForInvalidArgument() {
if (method_exists($this, 'expectException')) {
$this->expectException(InvalidArgumentException::class);
}
else {
$this->setExpectedException(InvalidArgumentException::class); $this->setExpectedException(InvalidArgumentException::class);
}
$this->container->get('invalid_argument_service'); $this->container->get('invalid_argument_service');
} }
@ -612,7 +687,12 @@ class ContainerTest extends TestCase {
public function testResolveServicesAndParametersForInvalidArguments() { public function testResolveServicesAndParametersForInvalidArguments() {
// In case the machine-optimized format is not used, we need to simulate the // In case the machine-optimized format is not used, we need to simulate the
// test failure. // test failure.
if (method_exists($this, 'expectException')) {
$this->expectException(InvalidArgumentException::class);
}
else {
$this->setExpectedException(InvalidArgumentException::class); $this->setExpectedException(InvalidArgumentException::class);
}
if (!$this->machineFormat) { if (!$this->machineFormat) {
throw new InvalidArgumentException('Simulating the test failure.'); throw new InvalidArgumentException('Simulating the test failure.');
} }

View File

@ -545,7 +545,12 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
$services['bar'] = $bar_definition; $services['bar'] = $bar_definition;
$this->containerBuilder->getDefinitions()->willReturn($services); $this->containerBuilder->getDefinitions()->willReturn($services);
if (method_exists($this, 'expectException')) {
$this->expectException(InvalidArgumentException::class);
}
else {
$this->setExpectedException(InvalidArgumentException::class); $this->setExpectedException(InvalidArgumentException::class);
}
$this->dumper->getArray(); $this->dumper->getArray();
} }
@ -562,7 +567,12 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
$services['bar'] = $bar_definition; $services['bar'] = $bar_definition;
$this->containerBuilder->getDefinitions()->willReturn($services); $this->containerBuilder->getDefinitions()->willReturn($services);
if (method_exists($this, 'expectException')) {
$this->expectException(RuntimeException::class);
}
else {
$this->setExpectedException(RuntimeException::class); $this->setExpectedException(RuntimeException::class);
}
$this->dumper->getArray(); $this->dumper->getArray();
} }
@ -579,7 +589,12 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
$services['bar'] = $bar_definition; $services['bar'] = $bar_definition;
$this->containerBuilder->getDefinitions()->willReturn($services); $this->containerBuilder->getDefinitions()->willReturn($services);
if (method_exists($this, 'expectException')) {
$this->expectException(RuntimeException::class);
}
else {
$this->setExpectedException(RuntimeException::class); $this->setExpectedException(RuntimeException::class);
}
$this->dumper->getArray(); $this->dumper->getArray();
} }
@ -596,7 +611,12 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
$services['bar'] = $bar_definition; $services['bar'] = $bar_definition;
$this->containerBuilder->getDefinitions()->willReturn($services); $this->containerBuilder->getDefinitions()->willReturn($services);
if (method_exists($this, 'expectException')) {
$this->expectException(RuntimeException::class);
}
else {
$this->setExpectedException(RuntimeException::class); $this->setExpectedException(RuntimeException::class);
}
$this->dumper->getArray(); $this->dumper->getArray();
} }

View File

@ -4,6 +4,7 @@ namespace Drupal\Tests\Component\Diff\Engine;
use Drupal\Component\Diff\Engine\DiffOp; use Drupal\Component\Diff\Engine\DiffOp;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Error\Error;
/** /**
* Test DiffOp base class. * Test DiffOp base class.
@ -24,7 +25,12 @@ class DiffOpTest extends TestCase {
* @covers ::reverse * @covers ::reverse
*/ */
public function testReverse() { public function testReverse() {
if (method_exists($this, 'expectException')) {
$this->expectException(Error::class);
}
else {
$this->setExpectedException(\PHPUnit_Framework_Error::class); $this->setExpectedException(\PHPUnit_Framework_Error::class);
}
$op = new DiffOp(); $op = new DiffOp();
$result = $op->reverse(); $result = $op->reverse();
} }

View File

@ -124,7 +124,13 @@ class YamlDirectoryDiscoveryTest extends TestCase {
* @covers ::getIdentifier * @covers ::getIdentifier
*/ */
public function testDiscoveryNoIdException() { public function testDiscoveryNoIdException() {
if (method_exists($this, 'expectException')) {
$this->expectException(DiscoveryException::class);
$this->expectExceptionMessage('The vfs://modules/test_1/item_1.test.yml contains no data in the identifier key \'id\'');
}
else {
$this->setExpectedException(DiscoveryException::class, 'The vfs://modules/test_1/item_1.test.yml contains no data in the identifier key \'id\''); $this->setExpectedException(DiscoveryException::class, 'The vfs://modules/test_1/item_1.test.yml contains no data in the identifier key \'id\'');
}
vfsStream::setup('modules', NULL, [ vfsStream::setup('modules', NULL, [
'test_1' => [ 'test_1' => [
'item_1.test.yml' => "", 'item_1.test.yml' => "",
@ -144,7 +150,13 @@ class YamlDirectoryDiscoveryTest extends TestCase {
* @covers ::findAll * @covers ::findAll
*/ */
public function testDiscoveryInvalidYamlException() { public function testDiscoveryInvalidYamlException() {
if (method_exists($this, 'expectException')) {
$this->expectException(DiscoveryException::class);
$this->expectExceptionMessage('The vfs://modules/test_1/item_1.test.yml contains invalid YAML');
}
else {
$this->setExpectedException(DiscoveryException::class, 'The vfs://modules/test_1/item_1.test.yml contains invalid YAML'); $this->setExpectedException(DiscoveryException::class, 'The vfs://modules/test_1/item_1.test.yml contains invalid YAML');
}
vfsStream::setup('modules', NULL, [ vfsStream::setup('modules', NULL, [
'test_1' => [ 'test_1' => [
'item_1.test.yml' => "id: invalid\nfoo : [bar}", 'item_1.test.yml' => "id: invalid\nfoo : [bar}",

View File

@ -38,7 +38,7 @@ class ContainerAwareEventDispatcherTest extends SymfonyContainerAwareEventDispat
// When passing in callables exclusively as listeners into the event // When passing in callables exclusively as listeners into the event
// dispatcher constructor, the event dispatcher must not attempt to // dispatcher constructor, the event dispatcher must not attempt to
// resolve any services. // resolve any services.
$container = $this->getMock(ContainerInterface::class); $container = $this->getMockBuilder(ContainerInterface::class)->getMock();
$container->expects($this->never())->method($this->anything()); $container->expects($this->never())->method($this->anything());
$firstListener = new CallableClass(); $firstListener = new CallableClass();
@ -73,7 +73,7 @@ class ContainerAwareEventDispatcherTest extends SymfonyContainerAwareEventDispat
// When passing in callables exclusively as listeners into the event // When passing in callables exclusively as listeners into the event
// dispatcher constructor, the event dispatcher must not attempt to // dispatcher constructor, the event dispatcher must not attempt to
// resolve any services. // resolve any services.
$container = $this->getMock(ContainerInterface::class); $container = $this->getMockBuilder(ContainerInterface::class)->getMock();
$container->expects($this->never())->method($this->anything()); $container->expects($this->never())->method($this->anything());
$firstListener = new CallableClass(); $firstListener = new CallableClass();

View File

@ -59,7 +59,13 @@ class FileCacheFactoryTest extends TestCase {
*/ */
public function testGetNoPrefix() { public function testGetNoPrefix() {
FileCacheFactory::setPrefix(NULL); FileCacheFactory::setPrefix(NULL);
if (method_exists($this, 'expectException')) {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Required prefix configuration is missing');
}
else {
$this->setExpectedException(\InvalidArgumentException::class, 'Required prefix configuration is missing'); $this->setExpectedException(\InvalidArgumentException::class, 'Required prefix configuration is missing');
}
FileCacheFactory::get('test_foo_settings', []); FileCacheFactory::get('test_foo_settings', []);
} }

View File

@ -5,7 +5,7 @@ namespace Drupal\Tests\Component\PhpStorage;
use Drupal\Component\PhpStorage\FileStorage; use Drupal\Component\PhpStorage\FileStorage;
use Drupal\Component\Utility\Random; use Drupal\Component\Utility\Random;
use org\bovigo\vfs\vfsStreamDirectory; use org\bovigo\vfs\vfsStreamDirectory;
use PHPUnit_Framework_Error_Warning; use PHPUnit\Framework\Error\Warning;
/** /**
* @coversDefaultClass \Drupal\Component\PhpStorage\FileStorage * @coversDefaultClass \Drupal\Component\PhpStorage\FileStorage
@ -99,7 +99,13 @@ class FileStorageTest extends PhpStorageTestBase {
'bin' => 'test', 'bin' => 'test',
]); ]);
$code = "<?php\n echo 'here';"; $code = "<?php\n echo 'here';";
$this->setExpectedException(PHPUnit_Framework_Error_Warning::class, 'mkdir(): Permission Denied'); if (method_exists($this, 'expectException')) {
$this->expectException(Warning::class);
$this->expectExceptionMessage('mkdir(): Permission Denied');
}
else {
$this->setExpectedException(\PHPUnit_Framework_Error_Warning::class, 'mkdir(): Permission Denied');
}
$storage->save('subdirectory/foo.php', $code); $storage->save('subdirectory/foo.php', $code);
} }

View File

@ -71,11 +71,17 @@ class ContextTest extends TestCase {
// Set expectation for exception. // Set expectation for exception.
if ($is_required) { if ($is_required) {
if (method_exists($this, 'expectException')) {
$this->expectException('Drupal\Component\Plugin\Exception\ContextException');
$this->expectExceptionMessage(sprintf("The %s context is required and not present.", $data_type));
}
else {
$this->setExpectedException( $this->setExpectedException(
'Drupal\Component\Plugin\Exception\ContextException', 'Drupal\Component\Plugin\Exception\ContextException',
sprintf("The %s context is required and not present.", $data_type) sprintf("The %s context is required and not present.", $data_type)
); );
} }
}
// Exercise getContextValue(). // Exercise getContextValue().
$this->assertEquals($context_value, $mock_context->getContextValue()); $this->assertEquals($context_value, $mock_context->getContextValue());

View File

@ -35,7 +35,7 @@ class DefaultFactoryTest extends TestCase {
*/ */
public function testGetPluginClassWithValidObjectPluginDefinition() { public function testGetPluginClassWithValidObjectPluginDefinition() {
$plugin_class = Cherry::class; $plugin_class = Cherry::class;
$plugin_definition = $this->getMock(PluginDefinitionInterface::class); $plugin_definition = $this->getMockBuilder(PluginDefinitionInterface::class)->getMock();
$plugin_definition->expects($this->atLeastOnce()) $plugin_definition->expects($this->atLeastOnce())
->method('getClass') ->method('getClass')
->willReturn($plugin_class); ->willReturn($plugin_class);
@ -50,7 +50,13 @@ class DefaultFactoryTest extends TestCase {
* @covers ::getPluginClass * @covers ::getPluginClass
*/ */
public function testGetPluginClassWithMissingClassWithArrayPluginDefinition() { public function testGetPluginClassWithMissingClassWithArrayPluginDefinition() {
if (method_exists($this, 'expectException')) {
$this->expectException(PluginException::class);
$this->expectExceptionMessage('The plugin (cherry) did not specify an instance class.');
}
else {
$this->setExpectedException(PluginException::class, 'The plugin (cherry) did not specify an instance class.'); $this->setExpectedException(PluginException::class, 'The plugin (cherry) did not specify an instance class.');
}
DefaultFactory::getPluginClass('cherry', []); DefaultFactory::getPluginClass('cherry', []);
} }
@ -60,8 +66,14 @@ class DefaultFactoryTest extends TestCase {
* @covers ::getPluginClass * @covers ::getPluginClass
*/ */
public function testGetPluginClassWithMissingClassWithObjectPluginDefinition() { public function testGetPluginClassWithMissingClassWithObjectPluginDefinition() {
$plugin_definition = $this->getMock(PluginDefinitionInterface::class); $plugin_definition = $this->getMockBuilder(PluginDefinitionInterface::class)->getMock();
if (method_exists($this, 'expectException')) {
$this->expectException(PluginException::class);
$this->expectExceptionMessage('The plugin (cherry) did not specify an instance class.');
}
else {
$this->setExpectedException(PluginException::class, 'The plugin (cherry) did not specify an instance class.'); $this->setExpectedException(PluginException::class, 'The plugin (cherry) did not specify an instance class.');
}
DefaultFactory::getPluginClass('cherry', $plugin_definition); DefaultFactory::getPluginClass('cherry', $plugin_definition);
} }
@ -71,7 +83,13 @@ class DefaultFactoryTest extends TestCase {
* @covers ::getPluginClass * @covers ::getPluginClass
*/ */
public function testGetPluginClassWithNotExistingClassWithArrayPluginDefinition() { public function testGetPluginClassWithNotExistingClassWithArrayPluginDefinition() {
if (method_exists($this, 'expectException')) {
$this->expectException(PluginException::class);
$this->expectExceptionMessage('Plugin (kiwifruit) instance class "\Drupal\plugin_test\Plugin\plugin_test\fruit\Kiwifruit" does not exist.');
}
else {
$this->setExpectedException(PluginException::class, 'Plugin (kiwifruit) instance class "\Drupal\plugin_test\Plugin\plugin_test\fruit\Kiwifruit" does not exist.'); $this->setExpectedException(PluginException::class, 'Plugin (kiwifruit) instance class "\Drupal\plugin_test\Plugin\plugin_test\fruit\Kiwifruit" does not exist.');
}
DefaultFactory::getPluginClass('kiwifruit', ['class' => '\Drupal\plugin_test\Plugin\plugin_test\fruit\Kiwifruit']); DefaultFactory::getPluginClass('kiwifruit', ['class' => '\Drupal\plugin_test\Plugin\plugin_test\fruit\Kiwifruit']);
} }
@ -82,11 +100,16 @@ class DefaultFactoryTest extends TestCase {
*/ */
public function testGetPluginClassWithNotExistingClassWithObjectPluginDefinition() { public function testGetPluginClassWithNotExistingClassWithObjectPluginDefinition() {
$plugin_class = '\Drupal\plugin_test\Plugin\plugin_test\fruit\Kiwifruit'; $plugin_class = '\Drupal\plugin_test\Plugin\plugin_test\fruit\Kiwifruit';
$plugin_definition = $this->getMock(PluginDefinitionInterface::class); $plugin_definition = $this->getMockBuilder(PluginDefinitionInterface::class)->getMock();
$plugin_definition->expects($this->atLeastOnce()) $plugin_definition->expects($this->atLeastOnce())
->method('getClass') ->method('getClass')
->willReturn($plugin_class); ->willReturn($plugin_class);
if (method_exists($this, 'expectException')) {
$this->expectException(PluginException::class);
}
else {
$this->setExpectedException(PluginException::class); $this->setExpectedException(PluginException::class);
}
DefaultFactory::getPluginClass('kiwifruit', $plugin_definition); DefaultFactory::getPluginClass('kiwifruit', $plugin_definition);
} }
@ -109,7 +132,7 @@ class DefaultFactoryTest extends TestCase {
*/ */
public function testGetPluginClassWithInterfaceWithObjectPluginDefinition() { public function testGetPluginClassWithInterfaceWithObjectPluginDefinition() {
$plugin_class = Cherry::class; $plugin_class = Cherry::class;
$plugin_definition = $this->getMock(PluginDefinitionInterface::class); $plugin_definition = $this->getMockBuilder(PluginDefinitionInterface::class)->getMock();
$plugin_definition->expects($this->atLeastOnce()) $plugin_definition->expects($this->atLeastOnce())
->method('getClass') ->method('getClass')
->willReturn($plugin_class); ->willReturn($plugin_class);
@ -125,7 +148,13 @@ class DefaultFactoryTest extends TestCase {
*/ */
public function testGetPluginClassWithInterfaceAndInvalidClassWithArrayPluginDefinition() { public function testGetPluginClassWithInterfaceAndInvalidClassWithArrayPluginDefinition() {
$plugin_class = Kale::class; $plugin_class = Kale::class;
if (method_exists($this, 'expectException')) {
$this->expectException(PluginException::class);
$this->expectExceptionMessage('Plugin "cherry" (Drupal\plugin_test\Plugin\plugin_test\fruit\Kale) must implement interface Drupal\plugin_test\Plugin\plugin_test\fruit\FruitInterface.');
}
else {
$this->setExpectedException(PluginException::class, 'Plugin "cherry" (Drupal\plugin_test\Plugin\plugin_test\fruit\Kale) must implement interface Drupal\plugin_test\Plugin\plugin_test\fruit\FruitInterface.'); $this->setExpectedException(PluginException::class, 'Plugin "cherry" (Drupal\plugin_test\Plugin\plugin_test\fruit\Kale) must implement interface Drupal\plugin_test\Plugin\plugin_test\fruit\FruitInterface.');
}
DefaultFactory::getPluginClass('cherry', ['class' => $plugin_class, 'provider' => 'core'], FruitInterface::class); DefaultFactory::getPluginClass('cherry', ['class' => $plugin_class, 'provider' => 'core'], FruitInterface::class);
} }
@ -136,11 +165,16 @@ class DefaultFactoryTest extends TestCase {
*/ */
public function testGetPluginClassWithInterfaceAndInvalidClassWithObjectPluginDefinition() { public function testGetPluginClassWithInterfaceAndInvalidClassWithObjectPluginDefinition() {
$plugin_class = Kale::class; $plugin_class = Kale::class;
$plugin_definition = $this->getMock(PluginDefinitionInterface::class); $plugin_definition = $this->getMockBuilder(PluginDefinitionInterface::class)->getMock();
$plugin_definition->expects($this->atLeastOnce()) $plugin_definition->expects($this->atLeastOnce())
->method('getClass') ->method('getClass')
->willReturn($plugin_class); ->willReturn($plugin_class);
if (method_exists($this, 'expectException')) {
$this->expectException(PluginException::class);
}
else {
$this->setExpectedException(PluginException::class); $this->setExpectedException(PluginException::class);
}
DefaultFactory::getPluginClass('cherry', $plugin_definition, FruitInterface::class); DefaultFactory::getPluginClass('cherry', $plugin_definition, FruitInterface::class);
} }

View File

@ -69,7 +69,12 @@ class DiscoveryTraitTest extends TestCase {
$method_ref = new \ReflectionMethod($trait, 'doGetDefinition'); $method_ref = new \ReflectionMethod($trait, 'doGetDefinition');
$method_ref->setAccessible(TRUE); $method_ref->setAccessible(TRUE);
// Call doGetDefinition, with $exception_on_invalid always TRUE. // Call doGetDefinition, with $exception_on_invalid always TRUE.
if (method_exists($this, 'expectException')) {
$this->expectException(PluginNotFoundException::class);
}
else {
$this->setExpectedException(PluginNotFoundException::class); $this->setExpectedException(PluginNotFoundException::class);
}
$method_ref->invoke($trait, $definitions, $plugin_id, TRUE); $method_ref->invoke($trait, $definitions, $plugin_id, TRUE);
} }
@ -106,7 +111,12 @@ class DiscoveryTraitTest extends TestCase {
->method('getDefinitions') ->method('getDefinitions')
->willReturn($definitions); ->willReturn($definitions);
// Call getDefinition(), with $exception_on_invalid always TRUE. // Call getDefinition(), with $exception_on_invalid always TRUE.
if (method_exists($this, 'expectException')) {
$this->expectException(PluginNotFoundException::class);
}
else {
$this->setExpectedException(PluginNotFoundException::class); $this->setExpectedException(PluginNotFoundException::class);
}
$trait->getDefinition($plugin_id, TRUE); $trait->getDefinition($plugin_id, TRUE);
} }

View File

@ -100,8 +100,13 @@ class StaticDiscoveryDecoratorTest extends TestCase {
$ref_decorated->setValue($mock_decorator, $mock_decorated); $ref_decorated->setValue($mock_decorator, $mock_decorated);
if ($exception_on_invalid) { if ($exception_on_invalid) {
if (method_exists($this, 'expectException')) {
$this->expectException('Drupal\Component\Plugin\Exception\PluginNotFoundException');
}
else {
$this->setExpectedException('Drupal\Component\Plugin\Exception\PluginNotFoundException'); $this->setExpectedException('Drupal\Component\Plugin\Exception\PluginNotFoundException');
} }
}
// Exercise getDefinition(). It calls parent::getDefinition(). // Exercise getDefinition(). It calls parent::getDefinition().
$this->assertEquals( $this->assertEquals(

View File

@ -123,8 +123,13 @@ class ReflectionFactoryTest extends TestCase {
// us to use one data set for this test method as well as // us to use one data set for this test method as well as
// testCreateInstance(). // testCreateInstance().
if ($plugin_id == 'arguments_no_constructor') { if ($plugin_id == 'arguments_no_constructor') {
if (method_exists($this, 'expectException')) {
$this->expectException('\ReflectionException');
}
else {
$this->setExpectedException('\ReflectionException'); $this->setExpectedException('\ReflectionException');
} }
}
// Finally invoke getInstanceArguments() on our mocked factory. // Finally invoke getInstanceArguments() on our mocked factory.
$ref = new \ReflectionClass($reflector_name); $ref = new \ReflectionClass($reflector_name);

View File

@ -87,7 +87,12 @@ foo:
* @covers ::errorHandler * @covers ::errorHandler
*/ */
public function testError() { public function testError() {
if (method_exists($this, 'expectException')) {
$this->expectException(InvalidDataTypeException::class);
}
else {
$this->setExpectedException(InvalidDataTypeException::class); $this->setExpectedException(InvalidDataTypeException::class);
}
YamlPecl::decode('foo: [ads'); YamlPecl::decode('foo: [ads');
} }

View File

@ -59,7 +59,12 @@ class YamlSymfonyTest extends YamlTestBase {
* @covers ::decode * @covers ::decode
*/ */
public function testError() { public function testError() {
if (method_exists($this, 'expectException')) {
$this->expectException(InvalidDataTypeException::class);
}
else {
$this->setExpectedException(InvalidDataTypeException::class); $this->setExpectedException(InvalidDataTypeException::class);
}
YamlSymfony::decode('foo: [ads'); YamlSymfony::decode('foo: [ads');
} }
@ -69,7 +74,13 @@ class YamlSymfonyTest extends YamlTestBase {
* @covers ::encode * @covers ::encode
*/ */
public function testObjectSupportDisabled() { public function testObjectSupportDisabled() {
if (method_exists($this, 'expectException')) {
$this->expectException(InvalidDataTypeException::class);
$this->expectExceptionMessage('Object support when dumping a YAML file has been disabled.');
}
else {
$this->setExpectedException(InvalidDataTypeException::class, 'Object support when dumping a YAML file has been disabled.'); $this->setExpectedException(InvalidDataTypeException::class, 'Object support when dumping a YAML file has been disabled.');
}
$object = new \stdClass(); $object = new \stdClass();
$object->foo = 'bar'; $object->foo = 'bar';
YamlSymfony::encode([$object]); YamlSymfony::encode([$object]);

View File

@ -96,9 +96,9 @@ class ArgumentsResolverTest extends TestCase {
* Tests getArgument() with a Route, Request, and Account object. * Tests getArgument() with a Route, Request, and Account object.
*/ */
public function testGetArgumentOrder() { public function testGetArgumentOrder() {
$a1 = $this->getMock('\Drupal\Tests\Component\Utility\Test1Interface'); $a1 = $this->getMockBuilder('\Drupal\Tests\Component\Utility\Test1Interface')->getMock();
$a2 = $this->getMock('\Drupal\Tests\Component\Utility\TestClass'); $a2 = $this->getMockBuilder('\Drupal\Tests\Component\Utility\TestClass')->getMock();
$a3 = $this->getMock('\Drupal\Tests\Component\Utility\Test2Interface'); $a3 = $this->getMockBuilder('\Drupal\Tests\Component\Utility\Test2Interface')->getMock();
$objects = [ $objects = [
't1' => $a1, 't1' => $a1,
@ -123,12 +123,18 @@ class ArgumentsResolverTest extends TestCase {
* Without the typehint, the wildcard object will not be passed to the callable. * Without the typehint, the wildcard object will not be passed to the callable.
*/ */
public function testGetWildcardArgumentNoTypehint() { public function testGetWildcardArgumentNoTypehint() {
$a = $this->getMock('\Drupal\Tests\Component\Utility\Test1Interface'); $a = $this->getMockBuilder('\Drupal\Tests\Component\Utility\Test1Interface')->getMock();
$wildcards = [$a]; $wildcards = [$a];
$resolver = new ArgumentsResolver([], [], $wildcards); $resolver = new ArgumentsResolver([], [], $wildcards);
$callable = function ($route) {}; $callable = function ($route) {};
if (method_exists($this, 'expectException')) {
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('requires a value for the "$route" argument.');
}
else {
$this->setExpectedException(\RuntimeException::class, 'requires a value for the "$route" argument.'); $this->setExpectedException(\RuntimeException::class, 'requires a value for the "$route" argument.');
}
$resolver->getArguments($callable); $resolver->getArguments($callable);
} }
@ -156,7 +162,13 @@ class ArgumentsResolverTest extends TestCase {
$resolver = new ArgumentsResolver($scalars, $objects, []); $resolver = new ArgumentsResolver($scalars, $objects, []);
$callable = function (\stdClass $foo) {}; $callable = function (\stdClass $foo) {};
if (method_exists($this, 'expectException')) {
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('requires a value for the "$foo" argument.');
}
else {
$this->setExpectedException(\RuntimeException::class, 'requires a value for the "$foo" argument.'); $this->setExpectedException(\RuntimeException::class, 'requires a value for the "$foo" argument.');
}
$resolver->getArguments($callable); $resolver->getArguments($callable);
} }
@ -167,7 +179,13 @@ class ArgumentsResolverTest extends TestCase {
*/ */
public function testHandleUnresolvedArgument($callable) { public function testHandleUnresolvedArgument($callable) {
$resolver = new ArgumentsResolver([], [], []); $resolver = new ArgumentsResolver([], [], []);
if (method_exists($this, 'expectException')) {
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('requires a value for the "$foo" argument.');
}
else {
$this->setExpectedException(\RuntimeException::class, 'requires a value for the "$foo" argument.'); $this->setExpectedException(\RuntimeException::class, 'requires a value for the "$foo" argument.');
}
$resolver->getArguments($callable); $resolver->getArguments($callable);
} }

View File

@ -26,8 +26,13 @@ class ColorTest extends TestCase {
*/ */
public function testHexToRgb($value, $expected, $invalid = FALSE) { public function testHexToRgb($value, $expected, $invalid = FALSE) {
if ($invalid) { if ($invalid) {
if (method_exists($this, 'expectException')) {
$this->expectException('InvalidArgumentException');
}
else {
$this->setExpectedException('InvalidArgumentException'); $this->setExpectedException('InvalidArgumentException');
} }
}
$this->assertSame($expected, Color::hexToRgb($value)); $this->assertSame($expected, Color::hexToRgb($value));
} }

View File

@ -77,7 +77,12 @@ class CryptTest extends TestCase {
* Key to use in hashing process. * Key to use in hashing process.
*/ */
public function testHmacBase64Invalid($data, $key) { public function testHmacBase64Invalid($data, $key) {
$this->setExpectedException(\InvalidArgumentException::class); if (method_exists($this, 'expectException')) {
$this->expectException('InvalidArgumentException');
}
else {
$this->setExpectedException('InvalidArgumentException');
}
Crypt::hmacBase64($data, $key); Crypt::hmacBase64($data, $key);
} }

View File

@ -343,7 +343,12 @@ class HtmlTest extends TestCase {
* @dataProvider providerTestTransformRootRelativeUrlsToAbsoluteAssertion * @dataProvider providerTestTransformRootRelativeUrlsToAbsoluteAssertion
*/ */
public function testTransformRootRelativeUrlsToAbsoluteAssertion($scheme_and_host) { public function testTransformRootRelativeUrlsToAbsoluteAssertion($scheme_and_host) {
if (method_exists($this, 'expectException')) {
$this->expectException(\AssertionError::class);
}
else {
$this->setExpectedException(\AssertionError::class); $this->setExpectedException(\AssertionError::class);
}
Html::transformRootRelativeUrlsToAbsolute('', $scheme_and_host); Html::transformRootRelativeUrlsToAbsolute('', $scheme_and_host);
} }

View File

@ -62,7 +62,12 @@ class RandomTest extends TestCase {
// There are fewer than 100 possibilities so an exception should occur to // There are fewer than 100 possibilities so an exception should occur to
// prevent infinite loops. // prevent infinite loops.
$random = new Random(); $random = new Random();
if (method_exists($this, 'expectException')) {
$this->expectException(\RuntimeException::class);
}
else {
$this->setExpectedException(\RuntimeException::class); $this->setExpectedException(\RuntimeException::class);
}
for ($i = 0; $i <= 100; $i++) { for ($i = 0; $i <= 100; $i++) {
$str = $random->name(1, TRUE); $str = $random->name(1, TRUE);
$names[$str] = TRUE; $names[$str] = TRUE;
@ -78,7 +83,12 @@ class RandomTest extends TestCase {
// There are fewer than 100 possibilities so an exception should occur to // There are fewer than 100 possibilities so an exception should occur to
// prevent infinite loops. // prevent infinite loops.
$random = new Random(); $random = new Random();
if (method_exists($this, 'expectException')) {
$this->expectException(\RuntimeException::class);
}
else {
$this->setExpectedException(\RuntimeException::class); $this->setExpectedException(\RuntimeException::class);
}
for ($i = 0; $i <= 100; $i++) { for ($i = 0; $i <= 100; $i++) {
$str = $random->string(1, TRUE); $str = $random->string(1, TRUE);
$names[$str] = TRUE; $names[$str] = TRUE;

View File

@ -17,7 +17,12 @@ class RectangleTest extends TestCase {
* @covers ::rotate * @covers ::rotate
*/ */
public function testWrongWidth() { public function testWrongWidth() {
if (method_exists($this, 'expectException')) {
$this->expectException(\InvalidArgumentException::class);
}
else {
$this->setExpectedException(\InvalidArgumentException::class); $this->setExpectedException(\InvalidArgumentException::class);
}
$rect = new Rectangle(-40, 20); $rect = new Rectangle(-40, 20);
} }
@ -27,7 +32,12 @@ class RectangleTest extends TestCase {
* @covers ::rotate * @covers ::rotate
*/ */
public function testWrongHeight() { public function testWrongHeight() {
if (method_exists($this, 'expectException')) {
$this->expectException(\InvalidArgumentException::class);
}
else {
$this->setExpectedException(\InvalidArgumentException::class); $this->setExpectedException(\InvalidArgumentException::class);
}
$rect = new Rectangle(40, 0); $rect = new Rectangle(40, 0);
} }

View File

@ -37,7 +37,7 @@ class SafeMarkupTest extends TestCase {
* @covers ::isSafe * @covers ::isSafe
*/ */
public function testIsSafe() { public function testIsSafe() {
$safe_string = $this->getMock('\Drupal\Component\Render\MarkupInterface'); $safe_string = $this->getMockBuilder('\Drupal\Component\Render\MarkupInterface')->getMock();
$this->assertTrue(SafeMarkup::isSafe($safe_string)); $this->assertTrue(SafeMarkup::isSafe($safe_string));
$string_object = new SafeMarkupTestString('test'); $string_object = new SafeMarkupTestString('test');
$this->assertFalse(SafeMarkup::isSafe($string_object)); $this->assertFalse(SafeMarkup::isSafe($string_object));

View File

@ -33,8 +33,13 @@ class UnicodeTest extends TestCase {
*/ */
public function testStatus($value, $expected, $invalid = FALSE) { public function testStatus($value, $expected, $invalid = FALSE) {
if ($invalid) { if ($invalid) {
if (method_exists($this, 'expectException')) {
$this->expectException('InvalidArgumentException');
}
else {
$this->setExpectedException('InvalidArgumentException'); $this->setExpectedException('InvalidArgumentException');
} }
}
Unicode::setStatus($value); Unicode::setStatus($value);
$this->assertEquals($expected, Unicode::getStatus()); $this->assertEquals($expected, Unicode::getStatus());
} }

View File

@ -578,7 +578,12 @@ class UrlHelperTest extends TestCase {
* @dataProvider providerTestExternalIsLocalInvalid * @dataProvider providerTestExternalIsLocalInvalid
*/ */
public function testExternalIsLocalInvalid($url, $base_url) { public function testExternalIsLocalInvalid($url, $base_url) {
if (method_exists($this, 'expectException')) {
$this->expectException(\InvalidArgumentException::class);
}
else {
$this->setExpectedException(\InvalidArgumentException::class); $this->setExpectedException(\InvalidArgumentException::class);
}
UrlHelper::externalIsLocal($url, $base_url); UrlHelper::externalIsLocal($url, $base_url);
} }

View File

@ -164,10 +164,6 @@ class EntityFormDisplayAccessControlHandlerTest extends UnitTestCase {
->willReturnMap([ ->willReturnMap([
['entity_display', $storage_access_control_handler], ['entity_display', $storage_access_control_handler],
]); ]);
$entity_type_manager
->expects($this->any())
->method('getFieldDefinitions')
->willReturn([]);
$entity_type_manager $entity_type_manager
->expects($this->any()) ->expects($this->any())
->method('getDefinition') ->method('getDefinition')

View File

@ -123,9 +123,6 @@ class EntityListBuilderTest extends UnitTestCase {
$url = $this->getMockBuilder('\Drupal\Core\Url') $url = $this->getMockBuilder('\Drupal\Core\Url')
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$url->expects($this->any())
->method('toArray')
->will($this->returnValue([]));
$url->expects($this->atLeastOnce()) $url->expects($this->atLeastOnce())
->method('mergeOptions') ->method('mergeOptions')
->with(['query' => ['destination' => '/foo/bar']]); ->with(['query' => ['destination' => '/foo/bar']]);

View File

@ -361,7 +361,7 @@ class KeyValueEntityStorageTest extends UnitTestCase {
$this->assertSame('foo', $entity->getOriginalId()); $this->assertSame('foo', $entity->getOriginalId());
$expected = ['id' => 'foo']; $expected = ['id' => 'foo'];
$entity->expects($this->once()) $entity->expects($this->atLeastOnce())
->method('toArray') ->method('toArray')
->will($this->returnValue($expected)); ->will($this->returnValue($expected));

View File

@ -21,6 +21,7 @@ use Drupal\Tests\UnitTestCase;
* would trigger another deprecation error. * would trigger another deprecation error.
* *
* @group Listeners * @group Listeners
* @group legacy
* *
* @coversDefaultClass \Drupal\deprecation_test\Deprecation\FixtureDeprecatedClass * @coversDefaultClass \Drupal\deprecation_test\Deprecation\FixtureDeprecatedClass
*/ */
@ -29,6 +30,8 @@ class DrupalStandardsListenerDeprecationTest extends UnitTestCase {
/** /**
* Exercise DrupalStandardsListener's coverage validation. * Exercise DrupalStandardsListener's coverage validation.
* *
* @expectedDeprecation Drupal\deprecation_test\Deprecation\FixtureDeprecatedClass is deprecated.
*
* @covers ::testFunction * @covers ::testFunction
*/ */
public function testDeprecation() { public function testDeprecation() {

View File

@ -102,12 +102,12 @@ class LoggerChannelTest extends UnitTestCase {
*/ */
public function providerTestLog() { public function providerTestLog() {
$account_mock = $this->getMock('Drupal\Core\Session\AccountInterface'); $account_mock = $this->getMock('Drupal\Core\Session\AccountInterface');
$account_mock->expects($this->exactly(2)) $account_mock->expects($this->any())
->method('id') ->method('id')
->will($this->returnValue(1)); ->will($this->returnValue(1));
$request_mock = $this->getMock('Symfony\Component\HttpFoundation\Request'); $request_mock = $this->getMock('Symfony\Component\HttpFoundation\Request', ['getClientIp']);
$request_mock->expects($this->exactly(2)) $request_mock->expects($this->any())
->method('getClientIp') ->method('getClientIp')
->will($this->returnValue('127.0.0.1')); ->will($this->returnValue('127.0.0.1'));
$request_mock->headers = $this->getMock('Symfony\Component\HttpFoundation\ParameterBag'); $request_mock->headers = $this->getMock('Symfony\Component\HttpFoundation\ParameterBag');

View File

@ -76,12 +76,6 @@ class PathProcessorTest extends UnitTestCase {
$language_manager->expects($this->any()) $language_manager->expects($this->any())
->method('getLanguageTypes') ->method('getLanguageTypes')
->will($this->returnValue([LanguageInterface::TYPE_INTERFACE])); ->will($this->returnValue([LanguageInterface::TYPE_INTERFACE]));
$language_manager->expects($this->any())
->method('getNegotiationMethods')
->will($this->returnValue($method_definitions));
$language_manager->expects($this->any())
->method('getNegotiationMethodInstance')
->will($this->returnValue($method_instance));
$method_instance->setLanguageManager($language_manager); $method_instance->setLanguageManager($language_manager);
$this->languageManager = $language_manager; $this->languageManager = $language_manager;

View File

@ -104,6 +104,7 @@ class ContextTest extends UnitTestCase {
$container = new Container(); $container = new Container();
$cache_context_manager = $this->getMockBuilder('Drupal\Core\Cache\CacheContextsManager') $cache_context_manager = $this->getMockBuilder('Drupal\Core\Cache\CacheContextsManager')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(['validateTokens'])
->getMock(); ->getMock();
$container->set('cache_contexts_manager', $cache_context_manager); $container->set('cache_contexts_manager', $cache_context_manager);
$cache_context_manager->expects($this->any()) $cache_context_manager->expects($this->any())

View File

@ -38,6 +38,7 @@ class BubbleableMetadataTest extends UnitTestCase {
if (!$b instanceof BubbleableMetadata) { if (!$b instanceof BubbleableMetadata) {
$renderer = $this->getMockBuilder('Drupal\Core\Render\Renderer') $renderer = $this->getMockBuilder('Drupal\Core\Render\Renderer')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(['mergeAttachments'])
->getMock(); ->getMock();
$renderer->expects($this->never()) $renderer->expects($this->never())
->method('mergeAttachments'); ->method('mergeAttachments');

View File

@ -116,6 +116,31 @@ trait PhpunitCompatibilityTrait {
} }
} }
/**
* Compatibility layer for PHPUnit 6 to support PHPUnit 4 code.
*
* @param mixed $class
* The expected exception class.
* @param string $message
* The expected exception message.
* @param int $exception_code
* The expected exception code.
*/
public function setExpectedException($class, $message = '', $exception_code = NULL) {
if (method_exists($this, 'expectException')) {
$this->expectException($class);
if (!empty($message)) {
$this->expectExceptionMessage($message);
}
if ($exception_code !== NULL) {
$this->expectExceptionCode($exception_code);
}
}
else {
parent::setExpectedException($class, $message, $exception_code);
}
}
/** /**
* Checks if the trait is used in a class that has a method. * Checks if the trait is used in a class that has a method.
* *

View File

@ -8,6 +8,7 @@
*/ */
use Drupal\Component\Assertion\Handle; use Drupal\Component\Assertion\Handle;
use PHPUnit\Runner\Version;
/** /**
* Finds all valid extension directories recursively within a given directory. * Finds all valid extension directories recursively within a given directory.
@ -166,3 +167,19 @@ date_default_timezone_set('Australia/Sydney');
// make PHP 5 and 7 handle assertion failures the same way, but this call does // make PHP 5 and 7 handle assertion failures the same way, but this call does
// not turn runtime assertions on if they weren't on already. // not turn runtime assertions on if they weren't on already.
Handle::register(); Handle::register();
// PHPUnit 4 to PHPUnit 6 bridge. Tests written for PHPUnit 4 need to work on
// PHPUnit 6 with a minimum of fuss.
if (class_exists('PHPUnit\Runner\Version') && version_compare(Version::id(), '6.1', '>=')) {
class_alias('\PHPUnit\Framework\AssertionFailedError', '\PHPUnit_Framework_AssertionFailedError');
class_alias('\PHPUnit\Framework\Constraint\Count', '\PHPUnit_Framework_Constraint_Count');
class_alias('\PHPUnit\Framework\Error\Error', '\PHPUnit_Framework_Error');
class_alias('\PHPUnit\Framework\Error\Warning', '\PHPUnit_Framework_Error_Warning');
class_alias('\PHPUnit\Framework\ExpectationFailedException', '\PHPUnit_Framework_ExpectationFailedException');
class_alias('\PHPUnit\Framework\Exception', '\PHPUnit_Framework_Exception');
class_alias('\PHPUnit\Framework\MockObject\Matcher\InvokedRecorder', '\PHPUnit_Framework_MockObject_Matcher_InvokedRecorder');
class_alias('\PHPUnit\Framework\SkippedTestError', '\PHPUnit_Framework_SkippedTestError');
class_alias('\PHPUnit\Framework\TestCase', '\PHPUnit_Framework_TestCase');
class_alias('\PHPUnit\Util\Test', '\PHPUnit_Util_Test');
class_alias('\PHPUnit\Util\XML', '\PHPUnit_Util_XML');
}