function UnitTestCase::setupMockIterator

Set up a traversable class mock to return specific items when iterated.

Test doubles for types extending \Traversable are required to implement \Iterator which requires setting up five methods. Instead, this helper can be used.

@template T of \PHPUnit\Framework\MockObject\MockObject&\Iterator @phpstan-param T $mock @phpstan-return T

Parameters

\PHPUnit\Framework\MockObject\MockObject&\Iterator $mock: A mock object mocking a traversable class.

array $items: The items to return when this mock is iterated.

Return value

\PHPUnit\Framework\MockObject\MockObject&\Iterator The same mock object ready to be iterated.

See also

https://github.com/sebastianbergmann/phpunit-mock-objects/issues/103

1 call to UnitTestCase::setupMockIterator()
EntityViewBuilderTest::testBuildComponents in core/tests/Drupal/Tests/Core/Entity/EntityViewBuilderTest.php
Tests build components using a mocked Iterator.

File

core/tests/Drupal/Tests/UnitTestCase.php, line 234

Class

UnitTestCase
Provides a base class and helpers for Drupal unit tests.

Namespace

Drupal\Tests

Code

protected function setupMockIterator(MockObject&\Iterator $mock, array $items) : MockObject&\Iterator {
  $iterator = new \ArrayIterator($items);
  foreach (get_class_methods(\Iterator::class) as $method) {
    $mock->method($method)
      ->willReturnCallback([
      $iterator,
      $method,
    ]);
  }
  return $mock;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.