Problem/Motivation

When you do something in a test which causes a container rebuild, the test class still have a stale container in $this->container.

This is an easy trap for test developers to fall into.

But we could easily mitigate it by warning of an attempt to access a stale container.

Steps to reproduce

Proposed resolution

Add a subclass or wrapper class of Container, to use in tests.

This adds:

protected bool $isStale;

public function setStale();

and wraps the call to get() with a check for whether it's stale, and throws an exception if it is.

Remaining tasks

User interface changes

Introduced terminology

API changes

Data model changes

Release notes snippet

Comments

joachim created an issue.

berdir’s picture

container is already a magic property that resolves to \Drupal::container() in functional tests, see \Drupal\Core\Test\TestSetupTrait::__get.

I thought we did that for kernel tests too, apparently not?

joachim’s picture

No, it's set in Drupal\KernelTests\KernelTestBase::bootKernel():

    $this->container = $kernel->getContainer();