Setting up the current_user service in Kernel test is not completely trivial because user account 0 and 1 need to be created, along with the related schema. A new ::setUpCurrentUser() method is available on \Drupal\Tests\user\Traits\UserCreationTrait to do just that.
The new method creates a random user account and sets it as current user. Unless explicitly specified, a regular user account will be created and set as current, after creating user account 0 and 1. Additionally, the method will ensure that at least the anonymous user account exists regardless of the specified user ID.
This is also leveraged by Drupal\KernelTests\Core\Entity\EntityKernelTestBase, and also Drupal\Tests\node\Traits\NodeCreationTrait if no node author is specified and the current_user service has not been set up yet.
Note that the current_user service should be set up before any entity type schema relying on the user entity type is installed. See https://www.drupal.org/node/3036689 for details.
class MyTest1 extends KernelTestBase {
use UserCreationTrait;
public static $modules = [ 'system', 'user'];
protected function setUp() {
parent::setUp();
// Sets up a regular authenticated user.
$this->setUpCurrentUser();
$this->installEntitySchema('my_entity_type');
}
public function testStuff1() {
// ...
}
}
class MyTest2 extends KernelTestBase {
use UserCreationTrait;
public static $modules = [ 'system', 'user'];
protected function setUp() {
parent::setUp();
// Sets up an anonymous user.
$this->setUpCurrentUser(['uid' => 0]);
$this->installEntitySchema('my_entity_type');
}
public function testStuff2() {
// ...
}
}
class MyTest3 extends KernelTestBase {
use UserCreationTrait;
public static $modules = [ 'system', 'user'];
protected function setUp() {
parent::setUp();
// Explicitly creates and sets up the root user.
$this->setUpCurrentUser(['uid' => 1]);
$this->installEntitySchema('my_entity_type');
}
public function testStuff3() {
// ...
}
}