You are here

public function FormBuilderTest::testGetCache in Drupal 10

Same name and namespace in other branches
  1. 8 core/tests/Drupal/Tests/Core/Form/FormBuilderTest.php \Drupal\Tests\Core\Form\FormBuilderTest::testGetCache()
  2. 9 core/tests/Drupal/Tests/Core/Form/FormBuilderTest.php \Drupal\Tests\Core\Form\FormBuilderTest::testGetCache()

Tests the getCache() method.

File

core/tests/Drupal/Tests/Core/Form/FormBuilderTest.php, line 422
Contains \Drupal\Tests\Core\Form\FormBuilderTest.

Class

FormBuilderTest
@coversDefaultClass \Drupal\Core\Form\FormBuilder @group Form

Namespace

Drupal\Tests\Core\Form

Code

public function testGetCache() {
  $form_id = 'test_form_id';
  $expected_form = $form_id();
  $expected_form['#token'] = FALSE;

  // FormBuilder::buildForm() will be called twice, but the form object will
  // only be called once due to caching.
  $form_arg = $this
    ->createMock('Drupal\\Core\\Form\\FormInterface');
  $form_arg
    ->expects($this
    ->exactly(2))
    ->method('getFormId')
    ->will($this
    ->returnValue($form_id));
  $form_arg
    ->expects($this
    ->once())
    ->method('buildForm')
    ->will($this
    ->returnValue($expected_form));

  // Do an initial build of the form and track the build ID.
  $form_state = (new FormState())
    ->addBuildInfo('files', [
    [
      'module' => 'node',
      'type' => 'pages.inc',
    ],
  ])
    ->setRequestMethod('POST')
    ->setCached();
  $form = $this->formBuilder
    ->buildForm($form_arg, $form_state);
  $cached_form = $form;
  $cached_form['#cache_token'] = 'csrf_token';

  // The form cache, form_state cache, and CSRF token validation will only be
  // called on the cached form.
  $this->formCache
    ->expects($this
    ->once())
    ->method('getCache')
    ->willReturn($form);

  // The final form build will not trigger any actual form building, but will
  // use the form cache.
  $form_state
    ->setExecuted();
  $input['form_id'] = $form_id;
  $input['form_build_id'] = $form['#build_id'];
  $form_state
    ->setUserInput($input);
  $this->formBuilder
    ->buildForm($form_arg, $form_state);
  $this
    ->assertEmpty($form_state
    ->getErrors());
}