VOOZH about

URL: https://deepwiki.com/WordPress/mcp-adapter/7.1-testing

⇱ Testing | WordPress/mcp-adapter | DeepWiki


Loading...
Menu

Testing

This page documents the testing infrastructure for the MCP Adapter, including test organization, fixtures, execution methods, and continuous integration. For information about setting up the development environment, see Development Environment. For code quality tools like PHPCS and PHPStan, see Code Quality.

Purpose and Scope

The MCP Adapter uses PHPUnit for automated testing within a Docker-based wp-env environment. This document covers:

  • Test directory structure and organization patterns
  • Test fixtures for simulating dependencies
  • Commands for executing tests locally and in CI
  • Patterns for writing unit and integration tests
  • Code coverage generation and reporting
  • Troubleshooting common test failures

Test Directory Structure

The test suite is organized into three main categories, each serving a distinct purpose in the testing strategy.


Directory Breakdown:

DirectoryPurposeDependencies
tests/Unit/Fast tests for pure PHP logic without WordPress integrationMock objects, test fixtures
tests/Integration/Tests that exercise WordPress APIs, filters, and full request flowWordPress core, wp-env
tests/Fixtures/Test doubles (stubs, fakes) for isolating componentsNone

Sources: docs/guides/testing.md13-17 tests/Fixtures/DummyAbility.php tests/Unit/Abilities/ExecuteAbilityAbilityTest.php

Test Fixtures

The test suite includes several fixture classes that provide controlled implementations of system interfaces for testing purposes.

DummyObservabilityHandler

Located at tests/Fixtures/DummyObservabilityHandler.php this fixture implements the observability interface by capturing event recording calls in memory.

Key Methods:

  • record_event(string $event_name, array $tags = [], float $duration = null) - Stores event data
  • get_events() - Returns array of captured events for assertions

Usage Pattern:


DummyErrorHandler

Located at tests/Fixtures/DummyErrorHandler.php this fixture captures error logging calls for verification.

Key Methods:

  • log(string $message, array $context = []) - Stores log entries
  • get_logs() - Returns array of captured log messages

Usage Pattern:


DummyAbility

Located at tests/Fixtures/DummyAbility.php this fixture provides pre-configured test abilities with various permission and execution scenarios.

Registered Abilities:

Ability NamePurposePermission ResultExecution Result
test/always-allowedSuccessful executiontrue['ok' => true, 'echo' => []]
test/permission-deniedPermission failurefalseShould not execute
test/permission-exceptionException in permissionThrows RuntimeExceptionNever executed
test/execute-exceptionException in executiontrueThrows RuntimeException
test/imageBinary contenttrueReturns image data with mimeType
test/resourceResource with URItrueReturns string content
test/promptPrompt with argumentstrueReturns message array

Registration Pattern:

tests/Fixtures/DummyAbility.php39-57 shows the registration lifecycle:

  1. Hook category registration to wp_abilities_api_categories_init
  2. Hook abilities registration to wp_abilities_api_init
  3. Fire hooks if not already fired
  4. Register abilities using wp_register_ability()

Cleanup Pattern:

tests/Fixtures/DummyAbility.php594-629 provides unregister_all() which removes all test abilities and the test category, ensuring test isolation.

Sources: tests/Fixtures/DummyAbility.php7-641 docs/guides/testing.md74-88

Running Tests

Environment Setup

Tests execute within a Docker container managed by wp-env, providing a consistent WordPress environment with all dependencies.


Start Environment:


This launches WordPress at http://localhost:8888 with admin credentials admin/password.

Sources: CONTRIBUTING.md63-67 docs/guides/testing.md24-31

Executing Tests


Command Reference:

CommandPurposeExample
npm run test:phpRun full test suiteAll unit + integration tests
npm run test:php -- --filter test_nameRun specific test method--filter test_execute_with_valid_ability
npm run test:php -- tests/Unit/Handlers/Run directoryAll handler tests
npm run test:php -- --filter "Tools.*"Pattern matchingAll tests containing "Tools"

Sources: docs/guides/testing.md33-56 CONTRIBUTING.md92-99

Code Coverage

Coverage reports require Xdebug in coverage mode. The coverage configuration is controlled through wp-env flags.

Enable Coverage:


Coverage Output Locations:

The XML format is used by CI/CD tools like Codecov for tracking coverage trends over time.

Sources: docs/guides/testing.md58-73

Writing Tests

Test Class Structure

Tests inherit from WP\MCP\Tests\TestCase which provides WordPress integration helpers and automatic test isolation.


Example Test Structure:

tests/Unit/Abilities/ExecuteAbilityAbilityTest.php18-59 demonstrates the standard pattern:


Sources: tests/Unit/Abilities/ExecuteAbilityAbilityTest.php1-481

Test Method Patterns

Each test follows the Arrange-Act-Assert (AAA) pattern with descriptive method names prefixed with test_.

Example: Permission Check Test

tests/Unit/Abilities/ExecuteAbilityAbilityTest.php72-80 shows testing the permission callback:


Example: Error Handling Test

tests/Unit/Abilities/ExecuteAbilityAbilityTest.php332-368 demonstrates WP_Error verification:


Using Test Fixtures

Fixtures enable isolated testing by replacing real implementations with controlled test doubles.

DummyAbility Usage:

tests/Fixtures/DummyAbility.php39-57 must be registered in test setup:


Testing with Annotations:

tests/Fixtures/DummyAbility.php271-292 provides abilities with specific annotation configurations for testing McpAnnotationMapper:


Sources: tests/Fixtures/DummyAbility.php7-641 tests/Unit/Abilities/ExecuteAbilityAbilityTest.php18-481

Continuous Integration

The CI/CD pipeline runs on GitHub Actions, testing across multiple PHP and WordPress versions.


Test Matrix Configuration:

DimensionValues
PHP Versions7.4, 8.0, 8.1, 8.2, 8.3, 8.4
WordPress Versionslatest, trunk
Total Combinations12

CI Steps:

  1. Checkout code
  2. Setup PHP and Composer
  3. Install dependencies
  4. Run PHPCS linting
  5. Run PHPStan static analysis (level 8)
  6. Execute PHPUnit tests
  7. Upload coverage (PHP 8.4 + WP latest only)

Coverage Reporting:

Only the PHP 8.4 + WordPress latest combination generates and uploads coverage to Codecov. This avoids redundant uploads while ensuring coverage is tracked.

Sources: docs/guides/testing.md153-167 CONTRIBUTING.md15-16

Troubleshooting

Common Test Failures

Class Not Found Errors

Symptom: Fatal error: Class 'WP\MCP\...' not found

Cause: Composer autoloader is out of sync after adding new classes, pulling changes, or switching branches.

Solution:


The --env-cwd flag ensures Composer operates within the plugin directory inside the Docker container.

Sources: docs/guides/testing.md138-142

Environment Issues

wp-env Start Failures

Solution: Clean and Restart:


Port Conflicts:

Default ports are 8888 (site) and 8889 (tests). If these are in use, either stop conflicting services or configure custom ports in .wp-env.json.

Permission Errors:

Ensure Docker has volume mount permissions. On Linux, this may require adding your user to the docker group.

Sources: docs/guides/testing.md122-145

Accessing Test Environment

Direct Access Methods:

ResourceURL/Command
WordPress Sitehttp://localhost:8888
Admin Dashboardhttp://localhost:8888/wp-admin/
Login Credentialsadmin / password
WP-CLInpm run wp-env run tests-cli YOUR_COMMAND

Example WP-CLI Commands:


Sources: docs/guides/testing.md147-151 CONTRIBUTING.md80-82

Test Isolation Issues

Symptom: Tests fail when run together but pass individually

Common Causes:

  1. Abilities not properly unregistered between tests
  2. Global state not reset (e.g., current user, filters)
  3. Singletons not cleared (e.g., McpAdapter::instance())

Solutions:

  • Use DummyAbility::unregister_all() in tear_down()
  • Reset current user: wp_set_current_user(0) in tear_down()
  • Clear server registry in integration tests if needed
  • Verify parent TestCase::tear_down() is called

Example Proper Cleanup:

tests/Unit/Abilities/ExecuteAbilityAbilityTest.php55-59 shows correct teardown:


Sources: tests/Unit/Abilities/ExecuteAbilityAbilityTest.php49-59 tests/Fixtures/DummyAbility.php594-629