You are here

protected function MockHelperTrait::prepareMock in Mini site 8

Helper to prepare class mock.

Parameters

string $class: Class name to generate the mock.

array|null $methodsMap: Optional array of methods and values, keyed by method name. If set to NULL, none of the methods will be mocked. Set to empty array if you want all methods to be mocked.

array $args: Optional array of constructor arguments. If omitted, a constructor will not be called.

Return value

object Mocked class.

File

tests/src/Traits/MockHelperTrait.php, line 90

Class

MockHelperTrait
Trait MockHelperTrait.

Namespace

Drupal\Tests\minisite\Traits

Code

protected function prepareMock($class, $methodsMap = [], array $args = []) {
  $methods = is_array($methodsMap) ? array_keys($methodsMap) : $methodsMap;
  $reflectionClass = new \ReflectionClass($class);
  if ($reflectionClass
    ->isAbstract()) {
    $mock = $this
      ->getMockForAbstractClass($class, $args, '', !empty($args), TRUE, TRUE, $methods);
  }
  else {
    $mock = $this
      ->getMockBuilder($class);
    if (!empty($args)) {
      $mock = $mock
        ->enableOriginalConstructor()
        ->setConstructorArgs($args);
    }
    else {
      $mock = $mock
        ->disableOriginalConstructor();
    }
    $mock = $mock
      ->setMethods($methods)
      ->getMock();
  }
  if (is_array($methodsMap)) {
    foreach ($methodsMap as $method => $value) {

      // Handle callback values differently.
      if (is_object($value) && strpos(get_class($value), 'Callback') !== FALSE) {
        $mock
          ->expects($this
          ->any())
          ->method($method)
          ->will($value);
      }
      else {
        $mock
          ->expects($this
          ->any())
          ->method($method)
          ->willReturn($value);
      }
    }
  }
  return $mock;
}