Testing

Running Tests

# Run all tests
composer test

# Or directly
vendor/bin/phpunit

# With coverage
vendor/bin/phpunit --coverage-html coverage/

Test Structure

tests/
+-- Unit/
    +-- PluginContextTest.php
    +-- ApplicationTest.php
    +-- PathsTest.php
    +-- Support/
        +-- ArrTest.php
        +-- StrTest.php

Writing Tests

Testing PluginContext

<?php

declare(strict_types=1);

namespace WPZylos\Framework\Core\Tests\Unit;

use PHPUnit\Framework\TestCase;
use WPZylos\Framework\Core\PluginContext;

class PluginContextTest extends TestCase
{
    private PluginContext $context;

    protected function setUp(): void
    {
        $this->context = PluginContext::create([
            'file' => '/path/to/plugin.php',
            'slug' => 'test-plugin',
            'prefix' => 'tp_',
            'textDomain' => 'test-plugin',
            'version' => '1.0.0',
        ]);
    }

    public function testSlugReturnsCorrectValue(): void
    {
        $this->assertSame('test-plugin', $this->context->slug());
    }

    public function testPrefixReturnsCorrectValue(): void
    {
        $this->assertSame('tp_', $this->context->prefix());
    }

    public function testHookPrefixesCorrectly(): void
    {
        $this->assertSame('tp_my_event', $this->context->hook('my_event'));
    }

    public function testOptionKeyPrefixesCorrectly(): void
    {
        $this->assertSame('tp_settings', $this->context->optionKey('settings'));
    }
}

Testing Utility Classes

<?php

declare(strict_types=1);

namespace WPZylos\Framework\Core\Tests\Unit\Support;

use PHPUnit\Framework\TestCase;
use WPZylos\Framework\Core\Support\Arr;

class ArrTest extends TestCase
{
    public function testGetRetrievesNestedValue(): void
    {
        $array = ['a' => ['b' => ['c' => 'value']]];
        $this->assertSame('value', Arr::get($array, 'a.b.c'));
    }

    public function testGetReturnsDefaultForMissingKey(): void
    {
        $array = ['a' => 1];
        $this->assertSame('default', Arr::get($array, 'b', 'default'));
    }

    public function testHasChecksNestedKeys(): void
    {
        $array = ['a' => ['b' => 1]];
        $this->assertTrue(Arr::has($array, 'a.b'));
        $this->assertFalse(Arr::has($array, 'a.c'));
    }
}

Mocking WordPress

For tests that need WordPress functions, create a bootstrap file:

// tests/bootstrap.php
<?php

// Define WordPress constants
define('ABSPATH', '/tmp/wordpress/');

// Mock WordPress functions
if (!function_exists('plugin_dir_path')) {
    function plugin_dir_path($file) {
        return dirname($file) . '/';
    }
}

if (!function_exists('plugin_dir_url')) {
    function plugin_dir_url($file) {
        return 'https://example.com/wp-content/plugins/' . basename(dirname($file)) . '/';
    }
}

Update phpunit.xml:

<phpunit bootstrap="tests/bootstrap.php">

CI Integration

Tests run automatically on GitHub Actions for PHP 8.1, 8.2, and 8.3. See .github/workflows/ci.yml.