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
| Rule | Foco |
|---|---|
wp-plugin-best-practices.md | Checklist de qualidade (15 secoes) |
wp-plugin-patterns.md | Padroes de arquitetura |
wp-plugin-security-checklist.md | Deep-dive de seguranca |
wp-plugin-workflow.md | Ciclo 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.phpRules:
- 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.phpRules:
- 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+)
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
| Layer | Target | Status |
|---|---|---|
| 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 |
| Overall | 70%+ | Em progresso |
Generate report:
composer test:coverage
# Output: .cache/coverage/index.html5. 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 dataComposer scripts:
{
"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:
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
<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)
composer check # Runs: @test + @check:style + @check:rector + @check:stanCoverage Enforcement
composer test:coverage -- --coverage-clover=coverage.xml
# Parse coverage.xml e falhar se abaixo do threshold8. Domain-Specific Test Priorities
| Dominio | Prioridade | Motivo |
|---|---|---|
| Entitlement | CRITICAL | Hub central, geracao de codigo, auto-creation |
| Organization | CRITICAL | Multi-tenant boundary, cascade operations |
| Order | HIGH | Fluxo financeiro, Stripe integration |
| Invoice | HIGH | Financeiro, Banco Inter gateway |
| License | HIGH | Provisionamento de plugins |
| Collaborator | HIGH | Permissoes, roles, Organization membership |
| Environment | MEDIUM | Cloudflare integration, DNS management |
| Service | MEDIUM | Labs/Dev projects |
| Quote | MEDIUM | Fluxo comercial HubSpot |
| TaxInvoice | MEDIUM | ISSNet integration |
| Contract | LOW | Documentos estaticos |
| Document | LOW | Documentos estaticos |
| Download | LOW | Dependencia de License |
| Affiliate | LOW | SolidAffiliate integration |
| ServiceRequest | LOW | Sub-dominio de Service |
9. Known Gaps (to address)
| Gap | Prioridade | Esforco |
|---|---|---|
| Webhook handler tests (HubSpot, Stripe, Banco Inter) | HIGH | 4-6h |
| JWT auth flow integration tests | HIGH | 3-4h |
| Organization boundary penetration tests | HIGH | 2-3h |
| REST controller tests (~81 endpoints) | HIGH | 8-12h |
| Inertia page controller tests | MEDIUM | 3-4h |
| Dual repository toggle tests | MEDIUM | 2h |
| Entitlement auto-creation flow tests | MEDIUM | 2-3h |
| Coverage threshold no CI | MEDIUM | 30min (apos 70% atingido) |
| Email migration tests (11 templates em classes/) | LOW | 2h |
10. Test Writing Guide for Claude Code
Ao implementar nova feature no middag-account:
- Comecar com domain test — escrever teste para entity/service primeiro
- Red then Green then Refactor — TDD quando pratico
- Mirror src/ structure em tests/ — localizacoes previsiveis
- Usar Brain\Monkey para WP function stubs em unit tests
- Nunca mock o que nao possui — usar interfaces do Domain/
- Testar behavior, nao implementation — testar public API, nao internals
- Edge cases sempre — null, empty, max, invalid status transitions
- Organization boundary — todo teste de integracao deve verificar isolamento multi-tenant
- JWT auth — testar com token valido, expirado, invalid signature, wrong org
- Entitlement cascade — testar que criacao de entitlement dispara criacao de recursos dependentes
MIDDAG Account WordPress Plugin Testing Strategy v1.0 — Morgan (@pm), Abril 2026