function StorageTestBase::testSetIfNotExists

Same name in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/KeyValueStore/StorageTestBase.php \Drupal\KernelTests\Core\KeyValueStore\StorageTestBase::testSetIfNotExists()
  2. 8.9.x core/tests/Drupal/KernelTests/Core/KeyValueStore/StorageTestBase.php \Drupal\KernelTests\Core\KeyValueStore\StorageTestBase::testSetIfNotExists()
  3. 11.x core/tests/Drupal/KernelTests/Core/KeyValueStore/StorageTestBase.php \Drupal\KernelTests\Core\KeyValueStore\StorageTestBase::testSetIfNotExists()

Tests the setIfNotExists() method.

File

core/tests/Drupal/KernelTests/Core/KeyValueStore/StorageTestBase.php, line 160

Class

StorageTestBase
Base class for testing key-value storages.

Namespace

Drupal\KernelTests\Core\KeyValueStore

Code

public function testSetIfNotExists() : void {
    $stores = $this->createStorage();
    $key = $this->randomMachineName();
    // Test that setIfNotExists() succeeds only the first time.
    for ($i = 0; $i <= 1; $i++) {
        // setIfNotExists() should be TRUE the first time (when $i is 0) and
        // FALSE the second time (when $i is 1).
        $this->assertEquals(!$i, $stores[0]->setIfNotExists($key, $this->objects[$i]));
        $this->assertEquals($this->objects[0], $stores[0]->get($key));
        // Verify that the other collection is not affected.
        $this->assertNull($stores[1]->get($key));
    }
    // Remove the item and try to set it again.
    $stores[0]->delete($key);
    $stores[0]->setIfNotExists($key, $this->objects[1]);
    // This time it should succeed.
    $this->assertEquals($this->objects[1], $stores[0]->get($key));
    // Verify that the other collection is still not affected.
    $this->assertNull($stores[1]->get($key));
}

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