function BlockViewBuilderTest::testBlockViewBuilderCacheOptional
Tests block render cache handling of cache-optional blocks.
File
- 
              core/modules/ block/ tests/ src/ Kernel/ BlockViewBuilderTest.php, line 236 
Class
- BlockViewBuilderTest
- Tests the block view builder.
Namespace
Drupal\Tests\block\KernelCode
public function testBlockViewBuilderCacheOptional() : void {
  // Verify cache handling for a non-empty block.
  $this->verifyRenderCacheHandling();
  // Create a block with a plugin implementing CacheOptionalInterface.
  $this->block = $this->controller
    ->create([
    'id' => 'test_block',
    'theme' => 'stark',
    'plugin' => 'test_cache_optional',
  ]);
  $this->block
    ->save();
  \Drupal::keyValue('block_test')->set('content', 'This is content for a block that is not render cached.');
  /** @var \Drupal\Core\Cache\VariationCacheFactoryInterface $variation_cache_factory */
  $variation_cache_factory = \Drupal::service('variation_cache_factory');
  $cache_bin = $variation_cache_factory->get('render');
  // Force a request via GET so we can test the render cache.
  $request = \Drupal::request();
  $request_method = $request->server
    ->get('REQUEST_METHOD');
  $request->setMethod('GET');
  // Test that an entry for the block is not created in the render cache.
  $build = $this->getBlockRenderArray();
  $cache_keys = [
    'entity_view',
    'block',
    'test_block',
  ];
  $markup = $this->renderer
    ->renderRoot($build);
  $this->assertTrue(str_contains((string) $markup, 'This is content for a block that is not render cached.'));
  $this->assertFalse($cache_bin->get($cache_keys, CacheableMetadata::createFromRenderArray($build)));
  // Confirm that build render array has no cache keys.
  $this->assertArrayNotHasKey('keys', $build['#cache']);
  // Restore the previous request method.
  $request->setMethod($request_method);
}Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.
