This page has moved and will be redirected soon. See Migrated topics for the complete list.

Database isolation attribute

To isolate database changes between tests, the Integration testing framework (ITF) implements the DbIsolation attribute. When the DbIsolation attribute is enabled, the ITF:

  • Starts a database transaction before the test/test case.
  • Avoids a database commit during the test/test case.
  • Restores the database after the test/test case.

Format

1
2
3
#[
    DbIsolation(bool $state = true)
]

Parameters

  • state
    • Enables or disables database isolation.

Test class attribute

Use test class declarations when a sequence of tests introduces changes to the database and relies on the changes made by each other. For example, typical CRUD tests: create -> read -> update -> delete. Every next test method relies on a database state after the previous one. If at any point of that sequence (after creation) the test method fails, the database will be polluted with test data. To apply a database rollback after the test class, create a separate test class with DbIsolation enabled at a class level.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#[
    DbIsolation(true)
]
class Some\EntityTest extends \PHPUnit\Framework\TestCase
{
    public function testCreate()
    {
        $this->object->setData($this->initialData)->save();
        $this->assertNotEmpty($this->object->getId());
        return $this->object->getId();
    }

    public function testRead($objectId)
    {
        $this->object->load($objectId);
        $this->assertEquals($this->initialData, $this->object->getData());
        return $objectId;
    }

    public function testUpdate($objectId)
    {
        $this->object->setData($newData)->save();
        $object = new Some_Entity();
        $object->load($objectId);
        $this->assertEquals($newData, $object->getData());
        return $objectId;
    }

    public function testDelete($objectId)
    {
        $this->object->delete();
        $object = new Some_Entity();
        $object->load($objectId);
        $this->assertEmpty($object->getData());
    }
}

Test method attribute

To isolate changes made to the database by a single test, enable the DbIsolation attribute for the test method.

1
2
3
4
5
6
7
8
9
10
11
#[
    DbIsolation(true)
]
public function testSave()
{
    $taxClassDataObject = $this->taxClassFactory->create();
    $taxClassDataObject->setClassName(self::SAMPLE_TAX_CLASS_NAME)
        ->setClassType(TaxClassManagementInterface::TYPE_CUSTOMER);
    $taxClassId = $this->taxClassRepository->save($taxClassDataObject);
    $this->assertEquals(self::SAMPLE_TAX_CLASS_NAME, $this->taxClassModel->load($taxClassId)->getClassName());
}