v1.31.0
conocimientotesting-patternsreferences/

workflow-test.md

Referencia que testing-patterns carga bajo demanda desde su SKILL.md.

testing-patternsskill
referencescarpeta
19.936 Btamaño
2026-10-06último cambio del pack

Se ejecuta solo bajo peticion explicita: /testing-patterns con intencion de ejecutar o generar, o una peticion del tipo "ejecuta los tests", "genera tests para X", "analiza la cobertura". El disparo semantico de la skill NUNCA llega hasta aqui: responde con el conocimiento del SKILL.md y para aqui.

Extended Thinking Mode

think hard - Analiza casos edge y genera tests exhaustivos cuando se soliciten.


1. Contexto del Proyecto

1.1 Detectar VCS y Solucion

DETECTAR tipo de VCS:
  - Buscar carpeta .git/ → Git
  - Ninguno → Sin VCS

DETECTAR el objetivo de compilacion (ADR-037: una sola funcion, no buscar .sln a mano):
  node "${CLAUDE_PLUGIN_ROOT}/hooks/build-target.js" --json
  - Exit 0 → usar 'objetivo' (puede ser una solucion O un .csproj: el SDK acepta los dos)
  - Exit 3 → mostrar 'candidatos' y preguntar cual usar (solucionActiva del Hilo es el default)
  - Exit 4 → informar: no hay codigo .NET que testear

1.2 Ubicacion de Tests

Location_note

MiProyecto/
├── _hilo/                         ← Metricas de tests
├── src/                  ← CODIGO Y TESTS
│   ├── MiSolucion.sln|.slnx       ← .slnx solo .NET 8+
│   ├── MyCompany.MyApp.Domain/
│   ├── MyCompany.MyApp.Application/
│   ├── MyCompany.MyApp.Tests/           ← Tests unitarios
│   ├── MyCompany.MyApp.Integration.Tests/ ← Tests integracion
│   └── MyCompany.MyApp.Blazor.Tests/    ← Tests bUnit (si Blazor)
└── docs/testing/                     ← Documentacion de pruebas
    ├── planes/
    ├── resultados/
    └── reportes/

2. Modos de Ejecucion

Modes_title

2.1 Modo Ejecutar (default: --run)

Ejecutar la suite de tests existente y mostrar resultados con cobertura.

2.2 Modo Generar (--generate)

Generar tests nuevos para codigo existente que no tiene tests.

2.3 Modo Analizar Cobertura (--coverage)

Analizar gaps de cobertura sin ejecutar tests, identificando clases/metodos sin tests.

2.4 Modo Filtrado (--filter)

Ejecutar tests filtrados por clase, metodo, categoria o proyecto.

Ejemplos de uso:
  /test                             → Ejecutar todos los tests
  /test --generate ScholarshipService      → Generar tests para ScholarshipService
  /test --coverage                  → Analizar gaps de cobertura
  /test --filter "ClassName"        → Filtrar tests por clase
  /test --project Tests.Unit        → Solo proyecto especifico
  /test --category integration      → Solo tests de integracion

3. MODO EJECUTAR: Flujo de 10 pasos

Paso 1: Detectar Framework de Tests

# Buscar proyectos de test en src/
$testProjects = Get-ChildItem -Path "src" -Recurse -Filter "*.csproj" |
    Where-Object { $_.Name -match "Test|Tests|Spec" }

# Detectar framework en cada .csproj:
# - xUnit       → <PackageReference Include="xunit" />
# - NUnit       → <PackageReference Include="NUnit" />
# - MSTest      → <PackageReference Include="MSTest.TestFramework" />
# - bUnit       → <PackageReference Include="bunit" />
# - Testcontainers → <PackageReference Include="Testcontainers" />

Paso 2: Mostrar Tests Disponibles

TEST DETECTADOS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Projects_header

Proyecto                              Framework    Tests
────────────────────────────────────────────────────────
src/MyCompany.MyApp.Tests    xUnit+Moq    ~[N]
src/MyCompany.MyApp.IT       xUnit+TC     ~[N]
src/MyCompany.MyApp.Blazor   bUnit        ~[N]

Total: [N] proyectos de test, ~[N] tests

Ejecutar: [T]odos / [U]nitarios / [I]ntegracion / [S]eleccionar

Paso 3: Verificar Prerequisitos

Antes de ejecutar, verificar:

  • Build compila sin errores
  • Docker running si hay Testcontainers (tests de integracion)
  • Connection strings disponibles si hay tests de BD
# Verificar build
Push-Location "src"
$buildResult = dotnet build --no-restore --verbosity quiet 2>&1
if ($LASTEXITCODE -ne 0) {
    # Mostrar errores de build y detener
}
Pop-Location

Paso 4: Ejecutar Tests

# Objetivo de compilacion (solucion o .csproj)
$target = node "$env:CLAUDE_PLUGIN_ROOT/hooks/build-target.js"

# Ejecutar con cobertura
dotnet test $target `
    --collect:"XPlat Code Coverage" `
    --results-directory "docs/testing/results" `
    --logger "console;verbosity=normal" `
    --settings "src/runsettings.xml" 2>$null

# Con filter (si se especifico)
dotnet test $target `
    --filter "FullyQualifiedName~ScholarshipServiceTests" `
    --collect:"XPlat Code Coverage"

# Solo proyecto especifico
dotnet test "src/MyCompany.MyApp.Tests/MyCompany.MyApp.Tests.csproj" `
    --collect:"XPlat Code Coverage"

Paso 5: Mostrar Resultados

RESULTADOS DE TESTS
━━━━━━━━━━━━━━━━━━━━━

  Pasaron:  [N]
  Fallaron: [N]
  Saltados: [N]

  Tiempo: [X]s

  Cobertura Global: [X]%

  Cobertura por Capa:
  ┌──────────────────────┬───────────┬──────────┬──────────┐
  │ Capa                 │ Cobertura │ Objetivo │ Estado   │
  ├──────────────────────┼───────────┼──────────┼──────────┤
  │ Domain               │ [X]%      │ 90%      │ [OK/WARN]│
  │ Application          │ [X]%      │ 80%      │ [OK/WARN]│
  │ Infrastructure       │ [X]%      │ 60%      │ [OK/WARN]│
  │ Presentation/Web     │ [X]%      │ 40%      │ [OK/WARN]│
  └──────────────────────┴───────────┴──────────┴──────────┘

  Code testeado: src/
  Resultados en:   docs/testing/results/

Paso 6: Detalle de Tests Fallidos

TESTS FALLIDOS
━━━━━━━━━━━━━━━━

1. ScholarshipServiceTests.Create_EmptyName_ThrowsValidationException
   Mensaje: Expected exception of type ValidationException but no exception was thrown
   Ubicacion: src/MyCompany.MyApp.Tests/Services/ScholarshipServiceTests.cs:45
   Sugerencia: Verificar que el servicio valida el nombre antes de crear

2. PeriodTests.Constructor_EndDateAnterior_ThrowsExcepcion
   Mensaje: Assert.Throws() failed - no exception thrown
   Ubicacion: src/MyCompany.MyApp.Tests/ValueObjects/PeriodTests.cs:28
   Sugerencia: Verificar validacion en constructor de Period

Ver detalle: (numero) | Corregir: (c) | Continuar: (Enter)

Paso 7: Analisis de Cobertura Gaps

GAPS DE COBERTURA DETECTADOS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Clases sin tests (ordenadas por criticidad):
  [ALTA]  ScholarshipService.cs         → 12 metodos publicos, 0 tests
  [ALTA]  StudentService.cs   → 8 metodos publicos, 0 tests
  [MEDIA] NotificacionService.cs → 5 metodos publicos, 2 tests (40%)
  [BAJA]  MappingProfile.cs      → 3 metodos, 0 tests

Metodos sin cobertura en clases testeadas:
  ScholarshipController.Update()       → Sin test de 404
  ScholarshipController.Delete()       → Sin test de autorizacion
  Period.SeSolapa()            → Sin test

Generar tests para gaps? (s/n/seleccionar)

Paso 8: Actualizar Estado

Actualizar _hilo/ESTADO_PROYECTO.json:

{
  "metricas": {
    "cobertura_tests": "[X]"
  }
}

Paso 9: Generar Reporte en docs/testing/

# Reporte de Tests - [FECHA]

## Resumen Ejecutivo
- **Total**: [N] tests en [N] proyectos
- **Resultado**: [PASARON] / [FALLARON] / [SALTADOS]
- **Cobertura Global**: [X]%
- **Tiempo Total**: [X]s

## Cobertura por Proyecto
| Proyecto | Tests | Pasaron | Fallaron | Cobertura |
|----------|-------|---------|----------|-----------|
| MyCompany.MyApp.Tests | [N] | [N] | [N] | [X]% |
| MyCompany.MyApp.IntegrationTests | [N] | [N] | [N] | [X]% |

## Cobertura por Capa
| Capa | Lineas | Cubiertos | Cobertura | Objetivo | Estado |
|------|--------|-----------|-----------|----------|--------|
| Domain | [N] | [N] | [X]% | 90% | [OK/WARN] |
| Application | [N] | [N] | [X]% | 80% | [OK/WARN] |
| Infrastructure | [N] | [N] | [X]% | 60% | [OK/WARN] |

## Tests Fallidos
[Detalle si los hay]

## Gaps de Cobertura
[Lista de clases/metodos sin tests]

## Recomendaciones
[Sugerencias basadas en gaps detectados]

---
*Generado por /test - Ovillo*

Guardar en docs/testing/results/reporte_tests_[FECHA].md

Paso 10: Resumen Final

RESUMEN DE TESTS
━━━━━━━━━━━━━━━━━━

Estado:    [ OK | FALLANDO]
Total:     [N] tests
Cobertura: [X]%
Tiempo:    [X]s
Reporte:   docs/testing/results/reporte_tests_[FECHA].md

Next_steps
  - /commit           → Si todo OK, hacer commit
  - /test --generate  → Generar tests para gaps
  - /revision         → Code review antes de commit

  testing-patterns skill:
  - patterns/builders.md           → Test data builders
  - patterns/mocking-avanzado.md   → Mocking avanzado con Moq
  - patterns/integration-fixtures.md → WebApplicationFactory + Testcontainers

4. MODO GENERAR: Flujo

Cuando se ejecuta /testing-patterns --generate [archivo|clase]:

4.1 Analizar Codigo Fuente

Leer el archivo/clase objetivo en src/
Identificar:
  - Metodos publicos
  - Dependencias inyectadas (constructor)
  - Validaciones existentes
  - Excepciones posibles
  - Value Objects y entidades
  - Flujos happy path y edge cases

4.2 Seleccionar Patron de Test

Usar el arbol de decision del skill testing-patterns:

¿Que estas testeando?
├── Entidad de Dominio    → Patron: Domain entity test (SKILL.md)
├── Value Object          → Patron: Value object test (SKILL.md)
├── Service/Handler       → Patron: Service test + mocking-avanzado.md
├── Controller/Endpoint   → Patron: API test + ApiTestBase.cs.template
├── Repositorio           → Patron: Integration test + integration-fixtures.md
├── Componente Blazor     → Patron: bUnit test (bunit-patterns.md)
└── Datos complejos       → Patron: Builder/Factory (builders.md / test-data-factory.md)

4.3 Generar Tests con Convenciones

Aplicar SIEMPRE las convenciones de tests.md:

  • Nomenclatura: Method_Scenario_ExpectedResult
  • Patron AAA: Arrange, Act, Assert (comentar cada seccion)
  • System Under Test: variable _sut
  • Mocking: Moq con Mock<IInterface>
  • Assertions: FluentAssertions (Should())
  • Async: CancellationToken en todos los metodos async

4.4 Template Base

// src/MyCompany.MyApp.Tests/[Carpeta]/[Clase]Tests.cs
using Xunit;
using Moq;
using FluentAssertions;

namespace MyCompany.MyApp.Tests.[Carpeta];

public class [Clase]Tests
{
    // Mocks de dependencias
    private readonly Mock<I[Dependencia1]> _[dep1]Mock;
    private readonly Mock<ILogger<[Clase]>> _loggerMock;
    private readonly [Clase] _sut; // System Under Test

    public [Clase]Tests()
    {
        _[dep1]Mock = new Mock<I[Dependencia1]>();
        _loggerMock = new Mock<ILogger<[Clase]>>();
        _sut = new [Clase](_[dep1]Mock.Object, _loggerMock.Object);
    }

    [Fact]
    public async Task [Metodo]_[EscenarioPositivo]_[ResultadoEsperado]()
    {
        // Arrange
        // ... setup mocks y datos

        // Act
        var result = await _sut.[Metodo]Async(...);

        // Assert
        result.Should().NotBeNull();
        _[dep1]Mock.Verify(x => x.[Metodo](...), Times.Once);
    }

    [Fact]
    public async Task [Metodo]_[EscenarioNegativo]_[ThrowsExcepcion]()
    {
        // Arrange
        // ... setup para fallo

        // Act
        var act = () => _sut.[Metodo]Async(...);

        // Assert
        await act.Should().ThrowAsync<[TipoExcepcion]>()
            .WithMessage("*[texto esperado]*");
    }

    [Theory]
    [InlineData("", false)]
    [InlineData(null, false)]
    [InlineData("valor valido", true)]
    public async Task [Metodo]_[VariosEscenarios]_[ResultadoVariable](
        string input, bool expectedValid)
    {
        // Arrange + Act + Assert parametrizado
    }
}

5. Umbrales de Cobertura Configurables

El umbral que gatea es el de coverage-gate.ps1 (G7/R18), con -CoverageLineMin y -CoverageBranchMin: es el único que puede parar un build, y vive donde se aplica.

Los de abajo son la referencia por capa de esta skill para decir dónde falta cobertura. No son una clave del Hilo: ESTADO_PROYECTO.json no declara metricas.umbrales_cobertura, y un tercer sitio donde fijar el mismo número es la contradicción entre fuentes que vigila check-drift (ADR-066).

CapaReferencia
domain90
application80
infrastructure60
presentation40
global70

Si no estan configurados, usar los defaults de CLAUDE_BASE.md:

  • Domain: 90%, Application: 80%, Infrastructure: 60%, Presentation: 40%

6. Integracion con Skill y Regla

Tabla de Referencia Cruzada

Necesitas...RecursoUbicacion
Ejecutar tests existentesEste workflow.claude/skills/testing-patterns/references/workflow-test.md
Convenciones y nomenclaturaRegla tests.md.claude/skills/tests/SKILL.md
Patron de test unitarioSKILL.md seccion "Plantillas".claude/skills/testing-patterns/SKILL.md
Builder pattern (datos)builders.md.claude/skills/testing-patterns/patterns/builders.md
Mocking avanzado (Moq)mocking-avanzado.md.claude/skills/testing-patterns/patterns/mocking-avanzado.md
Tests de integracionintegration-fixtures.md.claude/skills/testing-patterns/patterns/integration-fixtures.md
Snapshot testing (Verify)snapshot-testing.md.claude/skills/testing-patterns/patterns/snapshot-testing.md
Contract testing (API)api-contract-testing.md.claude/skills/testing-patterns/patterns/api-contract-testing.md
Performance testingperformance-testing.md.claude/skills/testing-patterns/patterns/performance-testing.md
Factory pattern (datos)test-data-factory.md.claude/skills/testing-patterns/patterns/test-data-factory.md
Tests Blazor (bUnit)bunit-patterns.md.claude/skills/testing-patterns/patterns/bunit-patterns.md
Base class unitariaTestBase.cs.template.claude/skills/testing-patterns/templates/TestBase.cs.template
Base class integracionIntegrationTestBase.cs.template.claude/skills/testing-patterns/templates/IntegrationTestBase.cs.template
Base class APIApiTestBase.cs.template.claude/skills/testing-patterns/templates/ApiTestBase.cs.template
Builder base con BogusFakeBuilder.cs.template.claude/skills/testing-patterns/templates/FakeBuilder.cs.template

7. Diagrama de Flujo

┌──────────────────────────────────────────────────────────────┐
│                       /test                                   │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  PASO 1: Detectar VCS + multi-solucion                      │
│     │                                                        │
│  PASO 2: Detectar framework (xUnit/NUnit/MSTest/bUnit)      │
│     │                                                        │
│  PASO 3: Verificar prerequisitos (build, Docker)            │
│     │                                                        │
│  ┌──┴───────────────────────────────────────────────┐       │
│  │  ¿Modo?                                          │       │
│  ├──────────────────────────────────────────────────┤       │
│  │  --run (default)  │  --generate  │  --coverage   │       │
│  │       │           │      │       │      │        │       │
│  │  PASO 4: dotnet   │ Analizar    │ Escanear     │       │
│  │  test + coverage  │ codigo      │ clases sin   │       │
│  │       │           │ fuente      │ tests         │       │
│  │  PASO 5: Show     │      │      │      │        │       │
│  │  resultados       │ Seleccionar │ Mostrar      │       │
│  │       │           │ patron      │ gaps          │       │
│  │  PASO 6: Detalle  │      │      │      │        │       │
│  │  fallidos         │ Generar     │ Sugerir      │       │
│  │       │           │ tests       │ prioridades   │       │
│  └──┬───────────────────────────────────────────────┘       │
│     │                                                        │
│  PASO 7: Analisis de gaps                                   │
│     │                                                        │
│  PASO 8: Actualizar _hilo/ESTADO_PROYECTO.json             │
│     │                                                        │
│  PASO 9: Generar reporte en docs/testing/results/          │
│     │                                                        │
│  PASO 10: Resumen + proximos pasos + skill refs             │
│                                                              │
└──────────────────────────────────────────────────────────────┘

8. Tabla Resumen del Comando

AspectoValor
Invocacion/testing-patterns
Version1.0.0
Modos--run (default), --generate, --coverage, --filter
Parametros--project, --category, --filter, --no-report
VCSGit
Multi-solucionSi (selector interactivo)
FrameworkxUnit, NUnit, MSTest, bUnit
CoberturaXPlat Code Coverage + umbrales configurables
Reportesdocs/testing/results/reporte_tests_[FECHA].md
Actualiza_hilo/ESTADO_PROYECTO.json → metricas.tests
Skill relacionadotesting-patterns (13 archivos, 7 patrones, 4 templates)
Regla relacionadatests.md (convenciones AAA, nomenclatura, cobertura)

9. Recordatorios Criticos

NUNCA

  • Ejecutar tests sin verificar que el build compila
  • Ignorar tests fallidos sin analizar la causa
  • Generar tests que dependan de orden de ejecucion
  • Hardcodear datos sensibles en tests (connection strings, passwords)
  • Usar Thread.Sleep en tests (usar Task.Delay o Polly)

SIEMPRE

  • Verificar build antes de ejecutar tests
  • Usar patron AAA con comentarios en cada seccion
  • Generar tests con nomenclatura Metodo_Escenario_Resultado
  • Incluir tests de happy path Y edge cases
  • Usar CancellationToken en metodos async
  • Actualizar metricas en _hilo/ESTADO_PROYECTO.json
  • Consultar testing-patterns skill para patrones avanzados

Comando /test - Ovillo

← Volver a la ficha de testing-patterns

Ovillo v1.31.0tag v1.31.0 (2026-10-06) · sin decisiones posteriores69 skills · 19 agents · 22 hooks · 3 reglas · 15 tools · 103 decisionesfuente: ovillo/.claude/skills/testing-patterns/references/workflow-test.mdCopyright 2026 Hugo Valer Rojas · Apache-2.0