englishdom/unitarum

PHPUnit库提供灵活更改的数据库测试数据

1.0.5 2024-02-23 16:24 UTC

This package is auto-updated.

Last update: 2024-09-23 17:47:38 UTC


README

提供并灵活更改PHPUnit测试数据的库

默认测试数据

测试数据使用实体。实体必须提供getIdsetId方法。如果需要,库提供具有这两个方法的EntityIdentifierInterface接口。

实体示例

class User
{
    protected $id;
    protected $name;
    protected $email;

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

测试数据示例

$entity = new Entity\User();
$entity->setId(1);
$entity->setName('Test');
$entity->setEmail('test@test.no');

return ['table_name' => $entity];

PhpUnit测试

在测试开始时,需要使用两个参数初始化Unitarum对象。第一个参数是包含测试数据的文件夹路径。第二个参数是连接到sqlitedsn连接字符串。

测试示例

use PHPUnit\Framework\TestCase;

class DatabaseTest extends TestCase
{
    protected static $unitarum;

    public static function setUpBeforeClass()
    {
        self::$unitarum = new Unitarum([
            OptionsInterface::FIXTURE_FOLDER_OPTION => '../data',
            OptionsInterface::DSN_OPTION => 'sqlite:data/sqlite.db',
        ]);
    }
}

在每个测试案例中,需要开始和回滚一个事务。

测试示例

class DatabaseTest extends TestCase
{
    protected static $unitarum;

    public static function setUpBeforeClass()
    {
        ...
    }
    
    public function setUp()
    {
        self::$unitarum->getDataBase()->startTransaction();
        // or notning
    }
    
    public function tearDown()
    {
        self::$unitarum->getDataBase()->rollbackTransaction();
        //or
        self::$unitarun->truncate();
    }
}

如果您不想使用事务,可以使用TRUNCATE数据。

设置测试数据

在测试中,您可以应用测试数据并更改其中任何数据。您可以调用初始化的unitarum对象的方法。调用方法名称必须等于测试数据文件名称。一个方法可以获取一个参数,即Entity。实体可以重写测试数据中的默认数据。

测试示例

class DatabaseTest extends TestCase
{
    ...
    
    public function testApplication()
    {
        $user = new Entity\User();
        $user->setEmail('newemail@email.no');
        
        $role = new Entity\Role();
        $role->setRole('viewer');
        $role->setUserId($user->getId());
        
        self::$unitarum->user($user)->role($role);
        
        // test
        ...
    }
}