Testing

Testing your database code with WPZylos Database.

Unit Testing

Mock Database

use PHPUnit\Framework\TestCase;
use WPZylos\Framework\Database\Connection;

class ProductRepositoryTest extends TestCase
{
    private Connection $db;

    protected function setUp(): void
    {
        parent::setUp();
        // Resolve Connection from the app container
        $this->db = $app->make(Connection::class);
    }

    public function testFindReturnsProduct(): void
    {
        $id = $this->db->table('products')->insert([
            'name' => 'Test Product',
            'price' => 99.99,
        ]);

        $product = $this->db->table('products')
            ->where('id', $id)
            ->first();

        $this->assertEquals('Test Product', $product->name);
    }
}

Transaction Testing

public function testTransactionRollsBackOnError(): void
{
    $initialCount = $this->db->table('orders')->count();

    try {
        $this->db->transaction(function () {
            $this->db->table('orders')->insert(['user_id' => 1]);
            throw new \Exception('Simulated error');
        });
    } catch (\Exception $e) {
        // Expected
    }

    $this->assertEquals($initialCount, $this->db->table('orders')->count());
}

Integration Testing

class DatabaseIntegrationTest extends WP_UnitTestCase
{
    public function setUp(): void
    {
        parent::setUp();
        $this->createTestTables();
    }

    public function tearDown(): void
    {
        $this->dropTestTables();
        parent::tearDown();
    }

    private function createTestTables(): void
    {
        global $wpdb;
        $wpdb->query("CREATE TABLE {$wpdb->prefix}test_users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255)
        )");
    }
}

Running Tests

composer run test