How to shadow a core function used in two different tests files? I have two tests files with tests that need to shadow the t() function in the Node Revision Delete project, one test file is placed in:

tests/src/Unit/Utility/TimeTest.php

And the other in:

tests/src/Unit/NodeRevisionDeleteTest.php

At this time I shadow the t() function with the same code at the end of each test file because the t() function is needed to run tests in both files.

namespace Drupal\node_revision_delete\Utility;

/**
 * Shadow t() system call.
 *
 * @param string $string
 *   A string containing the English text to translate.
 *
 * @return string
 *   The translated string.
 */
function t($string) {
  return $string;
}


When I run each test file all is working fine, but when I run all the project tests I get an error as I have declared the t() function twice:


  PHP Fatal error:  Cannot redeclare
  Drupal\node_revision_delete\Utility\t() (previously declared in
  /Users/adriancid/Sites/drupal84-test/modules/drupal.org/node_revision_delete/tests/src/Unit/NodeRevisionDeleteTest.php:357)
  in
  /Users/adriancid/Sites/drupal84-test/modules/drupal.org/node_revision_delete/tests/src/Unit/Utility/TimeTest.php
  on line 195


The only way that I found to make these works is to pass the tests that need the t() function from one test file to the other, but doing this I will have a mix of tests from diferent classes and I won't be able to use the @covers section in the test definition.

So, what is the correct way to shadow a core function used in two different tests files?
Wrap it in a !function_exists()

See core/tests/Drupal/Tests/Core/Render/Element/MachineNameTest.php for example:

&lt;?php

namespace Drupal\Core\Render\Element;

if (!function_exists('t')) {

  function t($string, array $args = []) {
    return strtr($string, $args);
  }

}


That said, t() as a specific example is deprecated and should not be used in classes, use the StringTranslationTrait/service instead and you can actually inject it.