Skip to content

WordPress Plugin Testing Strategy — MIDDAG Account

Estrategia de testes para o plugin middag-account com arquitetura DDD Light e 15 dominios. Claude Code: aplique esta estrategia ao escrever testes para o middag-account.

Companion Rules

RuleFoco
wp-plugin-best-practices.mdChecklist de qualidade (15 secoes)
wp-plugin-patterns.mdPadroes de arquitetura
wp-plugin-security-checklist.mdDeep-dive de seguranca
wp-plugin-workflow.mdCiclo de desenvolvimento

Test Pyramid

        /  E2E (manual/browser)  \        <-- Minimo: critical paths only
       /   Integration Tests      \       <-- WP bootstrap: REST, hooks, repos, webhooks
      /     Unit Tests             \      <-- No WP: domain logic, services (908 testes)
     /       Static Analysis        \     <-- PHPStan + PHP-CS-Fixer + Rector
    /-------------------------------|

1. Unit Tests (Domain Layer)

Scope: src/Domain/ — pure PHP, zero WordPress. 15 dominios.

Framework: PHPUnit 12 + Brain\Monkey (para WP function stubs).

O que testar:

  • Entities: construction, validation, state transitions
  • Value objects: immutability, equality, serialization
  • Services: business rules, calculos, edge cases
  • Enums: valid/invalid transitions, labels, state machine
  • Entitlement: geracao de codigo ({CLASSE}-{ANO}{MES}{SEQ:4d}), vinculo com dominios

Naming convention: tests/Unit/{mirrored-src-path}/{ClassName}Test.php

Estrutura por dominio (15 dominios):

tests/Unit/Domain/
  Organization/
    OrganizationEntityTest.php
    OrganizationServiceTest.php
  Collaborator/
    CollaboratorEntityTest.php
    CollaboratorRoleTest.php
  Order/
    OrderEntityTest.php
    OrderServiceTest.php
  Invoice/
    InvoiceEntityTest.php
    InvoiceServiceTest.php
  TaxInvoice/
    TaxInvoiceEntityTest.php
  License/
    LicenseEntityTest.php
    LicenseServiceTest.php
  Contract/
    ContractEntityTest.php
  Document/
    DocumentEntityTest.php
  Entitlement/
    EntitlementEntityTest.php
    EntitlementCodeGeneratorTest.php
    EntitlementServiceTest.php
  Environment/
    EnvironmentEntityTest.php
    EnvironmentServiceTest.php
  Service/
    ServiceEntityTest.php
    ServiceRequestEntityTest.php
  Quote/
    QuoteEntityTest.php
  Affiliate/
    AffiliateEntityTest.php
  Download/
    DownloadEntityTest.php

Rules:

  • Sem funcoes WordPress. Usar Brain\Monkey stubs se inevitavel.
  • Sem banco de dados. Mock repository interfaces.
  • Rapido: suite completa de unit em menos de 10 segundos.
  • Testar edge cases: null, empty, boundary values, invalid state transitions.
  • Entitlement code generation deve ser deterministico e testavel.

2. Integration Tests (WordPress Layer)

Scope: src/WordPress/, src/Api/, src/Integration/ — requer WP bootstrap.

Framework: PHPUnit 12 com WP test library (wp-phpunit).

O que testar:

REST API (~81 endpoints)

  • Autenticacao: JWT RS256, WP nonce, WC consumer keys
  • Authorization: Organization-scoped permissions
  • CRUD operations por dominio
  • Validation de input
  • Response format (envelope consistente)
  • Organization boundary enforcement (nao vazar dados cross-org)

Repositories

  • Create, read, update, delete via wp_posts CPT
  • Meta key mapping correto
  • Dual repository toggle (CCT <-> wp_posts)

JWT Auth Flow

  • Token issuance com RSA key pair
  • Token refresh com rotation
  • Token expiry e rejection
  • Invalid signature rejection
  • Organization claim validation

Webhook Handlers

  • HubSpot: signature validation, payload processing
  • Stripe: signature validation, event idempotency, dual-account
  • Banco Inter: callback validation, financial operation logging
  • Rejection de webhooks sem assinatura valida

Hooks

  • Verificar actions/filters disparam corretamente
  • Entitlement auto-creation no fluxo pagamento
  • Organization cascade (delete org -> cleanup dados)

Inertia Page Controllers

  • Props corretas enviadas para cada pagina
  • Authorization check no controller
  • Organization-scoped data filtering

Naming convention: tests/Integration/{Feature}/{FeatureName}Test.php

Estrutura:

tests/Integration/
  Auth/
    JwtAuthenticationTest.php
    JwtRefreshTest.php
  Api/
    OrganizationControllerTest.php
    EntitlementControllerTest.php
    OrderControllerTest.php
    ...
  Webhook/
    HubSpotWebhookTest.php
    StripeWebhookTest.php
    BancoInterWebhookTest.php
  Repository/
    OrganizationRepositoryTest.php
    DualRepositoryToggleTest.php
  MultiTenant/
    OrganizationBoundaryTest.php
    CrossOrgIsolationTest.php

Rules:

  • Usar test fixtures de tests/fixtures/.
  • Limpar dados criados apos cada teste.
  • Testar com multiplos user roles (admin, shop_manager, customer, anonymous).
  • Testar Organization boundary em TODA operacao de dados.
  • Verificar HTTP status codes e response structure para REST.

3. Static Analysis

PHPStan (Level 6+)

neon
parameters:
    level: 6
    paths: [src/]
    excludePaths: [vendor/]

Run: composer check:stan

PHP-CS-Fixer

Run: composer check:style (dry-run) / composer fix:style (apply)

Rector

Run: composer check:rector (dry-run) / composer fix:rector (apply)


4. Coverage Targets

LayerTargetStatus
Domain/ (entities, services, VOs)90%+908 tests, 3722 assertions
Api/ (controllers, ~81 endpoints)70%+Em desenvolvimento
Integration/ (HubSpot, Stripe, etc.)60%+Parcial
WordPress/ (hooks, admin, email)50%+Parcial
Overall70%+Em progresso

Generate report:

bash
composer test:coverage
# Output: .cache/coverage/index.html

5. Test Data Management

Fixtures

tests/fixtures/
  seed-organizations.php     # Sample organizations
  seed-entitlements.php      # Sample entitlements com todas 7 classes
  seed-orders.php            # Sample orders com invoices
  clean-test-data.php        # Remove all test data

Composer scripts:

json
{
    "seed": "wp eval-file tests/fixtures/seed-organizations.php",
    "seed:clean": "wp eval-file tests/fixtures/clean-test-data.php"
}

Factory Pattern

Para unit tests, factory functions que constroem entities com defaults sensiveis:

php
function createOrganizationEntity(array $overrides = []): OrganizationEntity {
    return new OrganizationEntity(array_merge([
        'name' => 'Test Organization',
        'cnpj' => '12.345.678/0001-00',
        'status' => OrganizationStatus::Active,
    ], $overrides));
}

function createEntitlementEntity(array $overrides = []): EntitlementEntity {
    return new EntitlementEntity(array_merge([
        'code' => 'PLG-2026040001',
        'class' => EntitlementClass::Plugin,
        'organization_id' => 1,
        'status' => EntitlementStatus::Active,
    ], $overrides));
}

6. PHPUnit Configuration

xml
<phpunit bootstrap="tests/bootstrap.php" colors="true">
    <testsuites>
        <testsuite name="Unit">
            <directory>tests/Unit</directory>
        </testsuite>
        <testsuite name="Integration">
            <directory>tests/Integration</directory>
        </testsuite>
    </testsuites>
    <source>
        <include>
            <directory>src</directory>
        </include>
        <exclude>
            <directory>src/Core</directory>
        </exclude>
    </source>
</phpunit>

7. CI Integration

Quality Gate (deve passar)

bash
composer check   # Runs: @test + @check:style + @check:rector + @check:stan

Coverage Enforcement

bash
composer test:coverage -- --coverage-clover=coverage.xml
# Parse coverage.xml e falhar se abaixo do threshold

8. Domain-Specific Test Priorities

DominioPrioridadeMotivo
EntitlementCRITICALHub central, geracao de codigo, auto-creation
OrganizationCRITICALMulti-tenant boundary, cascade operations
OrderHIGHFluxo financeiro, Stripe integration
InvoiceHIGHFinanceiro, Banco Inter gateway
LicenseHIGHProvisionamento de plugins
CollaboratorHIGHPermissoes, roles, Organization membership
EnvironmentMEDIUMCloudflare integration, DNS management
ServiceMEDIUMLabs/Dev projects
QuoteMEDIUMFluxo comercial HubSpot
TaxInvoiceMEDIUMISSNet integration
ContractLOWDocumentos estaticos
DocumentLOWDocumentos estaticos
DownloadLOWDependencia de License
AffiliateLOWSolidAffiliate integration
ServiceRequestLOWSub-dominio de Service

9. Known Gaps (to address)

GapPrioridadeEsforco
Webhook handler tests (HubSpot, Stripe, Banco Inter)HIGH4-6h
JWT auth flow integration testsHIGH3-4h
Organization boundary penetration testsHIGH2-3h
REST controller tests (~81 endpoints)HIGH8-12h
Inertia page controller testsMEDIUM3-4h
Dual repository toggle testsMEDIUM2h
Entitlement auto-creation flow testsMEDIUM2-3h
Coverage threshold no CIMEDIUM30min (apos 70% atingido)
Email migration tests (11 templates em classes/)LOW2h

10. Test Writing Guide for Claude Code

Ao implementar nova feature no middag-account:

  1. Comecar com domain test — escrever teste para entity/service primeiro
  2. Red then Green then Refactor — TDD quando pratico
  3. Mirror src/ structure em tests/ — localizacoes previsiveis
  4. Usar Brain\Monkey para WP function stubs em unit tests
  5. Nunca mock o que nao possui — usar interfaces do Domain/
  6. Testar behavior, nao implementation — testar public API, nao internals
  7. Edge cases sempre — null, empty, max, invalid status transitions
  8. Organization boundary — todo teste de integracao deve verificar isolamento multi-tenant
  9. JWT auth — testar com token valido, expirado, invalid signature, wrong org
  10. Entitlement cascade — testar que criacao de entitlement dispara criacao de recursos dependentes

MIDDAG Account WordPress Plugin Testing Strategy v1.0 — Morgan (@pm), Abril 2026