Testing

Testing your migrations with WPZylos Migrations.

Unit Testing

Testing Migration Up

use PHPUnit\Framework\TestCase;

class CreateProductsTableTest extends TestCase
{
    public function testMigrationCreatesTable(): void
    {
        global $wpdb;

        $migration = require 'database/migrations/2024_01_15_create_products_table.php';
        $migration->setConnection($this->db);
        $migration->up();

        $tableName = $wpdb->prefix . 'myplugin_products';
        $exists = $wpdb->get_var("SHOW TABLES LIKE '{$tableName}'") === $tableName;

        $this->assertTrue($exists);
    }

    public function testMigrationDown(): void
    {
        global $wpdb;

        $migration = require 'database/migrations/2024_01_15_create_products_table.php';
        $migration->setConnection($this->db);
        $migration->up();
        $migration->down();

        $tableName = $wpdb->prefix . 'myplugin_products';
        $exists = $wpdb->get_var("SHOW TABLES LIKE '{$tableName}'") === $tableName;

        $this->assertFalse($exists);
    }
}

Testing Migrator

class MigratorTest extends TestCase
{
    private Migrator $migrator;

    protected function setUp(): void
    {
        $this->migrator = new Migrator(
            $this->createContext(),
            $this->createConnection(),
            $this->createRepository()
        );
    }

    public function testRunReturnsRanMigrations(): void
    {
        $ran = $this->migrator->run();

        $this->assertIsArray($ran);
        $this->assertNotEmpty($ran);
    }

    public function testRollbackRevertsLastBatch(): void
    {
        $this->migrator->run();
        $rolledBack = $this->migrator->rollback();

        $this->assertIsArray($rolledBack);
    }

    protected function tearDown(): void
    {
        // Rollback all by passing a large step count
        $ran = $this->migrator->status();
        $this->migrator->rollback(count($ran));
    }
}

Running Tests

composer run test