TranslatableMarkupTest.php in Drupal 9
File
core/tests/Drupal/Tests/Core/StringTranslation/TranslatableMarkupTest.php
View source
<?php
namespace Drupal\Tests\Core\StringTranslation;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Tests\UnitTestCase;
class TranslatableMarkupTest extends UnitTestCase {
protected $lastErrorMessage;
protected $lastErrorNumber;
public function errorHandler($error_number, $error_message) {
$this->lastErrorNumber = $error_number;
$this->lastErrorMessage = $error_message;
}
public function testToString() {
$translation = $this
->createMock(TranslationInterface::class);
$string = 'May I have an exception please?';
$text = $this
->getMockBuilder(TranslatableMarkup::class)
->setConstructorArgs([
$string,
[],
[],
$translation,
])
->setMethods([
'_die',
])
->getMock();
$text
->expects($this
->once())
->method('_die')
->willReturn('');
$translation
->method('translateString')
->with($text)
->willReturnCallback(function () {
throw new \Exception('Yes you may.');
});
set_error_handler([
$this,
'errorHandler',
]);
(string) $text;
restore_error_handler();
$this
->assertEquals(E_USER_ERROR, $this->lastErrorNumber);
$this
->assertMatchesRegularExpression('/Exception thrown while calling __toString on a .*Mock_TranslatableMarkup_.* object in .*TranslatableMarkupTest.php on line [0-9]+: Yes you may./', $this->lastErrorMessage);
}
public function testIsStringAssertion() {
$translation = $this
->getStringTranslationStub();
$this
->expectException(\InvalidArgumentException::class);
$this
->expectExceptionMessage('$string ("foo") must be a string.');
new TranslatableMarkup(new TranslatableMarkup('foo', [], [], $translation));
}
public function testIsStringAssertionWithFormattableMarkup() {
$formattable_string = new FormattableMarkup('@bar', [
'@bar' => 'foo',
]);
$this
->expectException(\InvalidArgumentException::class);
$this
->expectExceptionMessage('$string ("foo") must be a string.');
new TranslatableMarkup($formattable_string);
}
}