This document outlines the testing strategy and patterns used in OPcache Toolkit.
OPcache Toolkit uses a multi-layered testing approach to ensure reliability and maintainability:
- Unit Tests (PHP): Isolated logic testing using PHPUnit and Brain\Monkey.
- Integration Tests (PHP): WordPress-dependent testing for database and REST API interactions.
- Frontend Tests (JS): Service and utility testing using Jest.
Unit tests are located in tests/phpunit/unit. They should extend OPcacheToolkit\Tests\Unit\BaseTestCase.
- Isolate Logic: Mock all external dependencies, including WordPress functions and other plugin services.
- No Database: Unit tests should never touch the database. Use mocks for
$wpdbor Repositories. - Brain\Monkey: Use
Monkey\Functions\when()orexpect()to mock global WordPress functions.
use Brain\Monkey;
public function test_something() {
Monkey\Functions\expect( 'get_option' )
->with( 'my_option' )
->andReturn( 'mock_value' );
$result = my_function_that_calls_get_option();
$this->assertEquals( 'mock_value', $result );
}$opcache = Mockery::mock( OPcacheService::class );
$opcache->shouldReceive( 'is_enabled' )->andReturn( true );
$command = new ResetCommand( $opcache );Integration tests are located in tests/phpunit/integration. They extend WP_UnitTestCase.
- WordPress Environment: These tests run with a full WordPress environment and a temporary database.
- REST API Testing: Use
WP_REST_Requestandrest_get_server()->dispatch()to test endpoints. - Database Verification: Use
$wpdbor plugin repositories to verify data persistence.
When testing REST endpoints that depend on services, you may need to mock the service within the plugin container.
public function set_up() {
parent::set_up();
// Mock OPcache and re-register endpoints.
$opcache = $this->createMock( \OPcacheToolkit\Services\OPcacheService::class );
$opcache->method( 'is_enabled' )->willReturn( true );
\OPcacheToolkit\Plugin::set_opcache( $opcache );
add_action( 'rest_api_init', [ \OPcacheToolkit\Plugin::instance(), 'register_rest_endpoints' ], 5 );
do_action( 'rest_api_init' );
}Frontend tests are located in tests/jest. They use Jest as the test runner.
Use jest.fn() to mock API modules or services.
import { getStatus } from '../../src/js/api/status';
jest.mock('../../src/js/api/status');
test('fetches status', async () => {
getStatus.mockResolvedValue({ success: true, data: { opcache_enabled: true } });
// ... test logic
});Coverage reporting is enabled for both Unit and Integration tests.
- Run Unit Coverage:
composer test:coverage - Outputs:
coverage-unit.xml(Clover)coverage-unit-html/(HTML Report)coverage-integration.xmlcoverage-integration-html/
All new code should aim for at least 80% coverage of business logic.