function UserEntityTest::testUserMethods

Same name in other branches
  1. 8.9.x core/modules/user/tests/src/Kernel/UserEntityTest.php \Drupal\Tests\user\Kernel\UserEntityTest::testUserMethods()
  2. 10 core/modules/user/tests/src/Kernel/UserEntityTest.php \Drupal\Tests\user\Kernel\UserEntityTest::testUserMethods()
  3. 11.x core/modules/user/tests/src/Kernel/UserEntityTest.php \Drupal\Tests\user\Kernel\UserEntityTest::testUserMethods()

Tests some of the methods.

See also

\Drupal\user\Entity\User::getRoles()

\Drupal\user\Entity\User::addRole()

\Drupal\user\Entity\User::removeRole()

File

core/modules/user/tests/src/Kernel/UserEntityTest.php, line 39

Class

UserEntityTest
Tests the user entity class.

Namespace

Drupal\Tests\user\Kernel

Code

public function testUserMethods() {
    $role_storage = $this->container
        ->get('entity_type.manager')
        ->getStorage('user_role');
    $role_storage->create([
        'id' => 'test_role_one',
        'label' => 'Test role 1',
    ])
        ->save();
    $role_storage->create([
        'id' => 'test_role_two',
        'label' => 'Test role 2',
    ])
        ->save();
    $role_storage->create([
        'id' => 'test_role_three',
        'label' => 'Test role 3',
    ])
        ->save();
    $values = [
        'uid' => 1,
        'roles' => [
            'test_role_one',
        ],
    ];
    $user = User::create($values);
    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertFalse($user->hasRole('test_role_two'));
    $this->assertEquals([
        RoleInterface::AUTHENTICATED_ID,
        'test_role_one',
    ], $user->getRoles());
    $user->addRole('test_role_one');
    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertFalse($user->hasRole('test_role_two'));
    $this->assertEquals([
        RoleInterface::AUTHENTICATED_ID,
        'test_role_one',
    ], $user->getRoles());
    $user->addRole('test_role_two');
    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertTrue($user->hasRole('test_role_two'));
    $this->assertEquals([
        RoleInterface::AUTHENTICATED_ID,
        'test_role_one',
        'test_role_two',
    ], $user->getRoles());
    $user->removeRole('test_role_three');
    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertTrue($user->hasRole('test_role_two'));
    $this->assertEquals([
        RoleInterface::AUTHENTICATED_ID,
        'test_role_one',
        'test_role_two',
    ], $user->getRoles());
    $user->removeRole('test_role_one');
    $this->assertFalse($user->hasRole('test_role_one'));
    $this->assertTrue($user->hasRole('test_role_two'));
    $this->assertEquals([
        RoleInterface::AUTHENTICATED_ID,
        'test_role_two',
    ], $user->getRoles());
}

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