Probar gratis
7 min lectura Guide 844 of 877

Estrategias de Testing Automatizado

Las estrategias de testing automatizado proporcionan feedback rápido y previenen regresiones en el desarrollo. GitScrum ayuda a los equipos a rastrear ejecución de tests y gestionar flujos de trabajo de testing a lo largo del ciclo de vida del desarrollo.

La Pirámide de Testing

PIRÁMIDE DE TESTING
═══════════════════

                    ▲
                   /│\
                  / │ \ E2E Tests
                 /  │  \ (Pocos, Lentos)
                /───┼───\
               /    │    \ Tests de
              /     │     \ Integración
             /──────┼──────\ (Algunos)
            /       │       \
           /        │        \ Tests Unitarios
          /─────────┴─────────\ (Muchos, Rápidos)

DISTRIBUCIÓN RECOMENDADA:
├── Tests Unitarios: 70%
├── Tests Integración: 20%
└── Tests E2E: 10%

CARACTERÍSTICAS:
┌─────────────┬─────────────┬─────────────┬─────────────┐
│ Nivel       │ Cantidad    │ Velocidad   │ Costo       │
├─────────────┼─────────────┼─────────────┼─────────────┤
│ E2E         │ Pocos       │ Lento       │ Alto        │
│ Integración │ Moderado    │ Medio       │ Medio       │
│ Unitarios   │ Muchos      │ Rápido      │ Bajo        │
└─────────────┴─────────────┴─────────────┴─────────────┘

Flujo de Trabajo de Test Automation

FLUJO DE TESTING AUTOMATIZADO
═════════════════════════════

┌─────────┐    ┌─────────────┐    ┌──────────────┐    ┌────────────┐
│ Escribir│───►│ Ejecutar    │───►│ Analizar     │───►│ Arreglar   │
│ Tests   │    │ en CI       │    │ Resultados   │    │ Fallos     │
└─────────┘    └─────────────┘    └──────────────┘    └────────────┘
      │              │                   │                   │
      ▼              ▼                   ▼                   ▼
   TDD/BDD      Ejecución          Reportes de        Prevención de
               Paralela           Cobertura          Regresiones

INTEGRACIÓN CON GITSCRUM:
├── Tareas de testing enlazadas a features
├── Estado de tests visible en dashboard
├── Métricas de cobertura rastreadas
└── Alertas en fallos de tests

Tipos de Tests y Cuándo Usarlos

Tests Unitarios

TESTS UNITARIOS
═══════════════

PROPÓSITO:
├── Verificar funciones/métodos individuales
├── Aislados de dependencias externas
├── Feedback instantáneo (milisegundos)
└── Base de la pirámide

EJEMPLO (Python):
┌─────────────────────────────────────────────────┐
│ def test_calculate_discount():                  │
│     cart = ShoppingCart()                       │
│     cart.add_item(Product("Widget", 100))       │
│     cart.apply_discount(10)                     │
│                                                 │
│     assert cart.total == 90                     │
│     assert cart.discount_applied == True        │
└─────────────────────────────────────────────────┘

HERRAMIENTAS:
├── Python: pytest, unittest
├── JavaScript: Jest, Vitest
├── Java: JUnit, TestNG
└── C#: xUnit, NUnit

COBERTURA OBJETIVO: >80%

Tests de Integración

TESTS DE INTEGRACIÓN
════════════════════

PROPÓSITO:
├── Verificar interacciones entre componentes
├── Probar flujo de datos real
├── Identificar problemas de integración
└── Usar dependencias reales o mocks realistas

EJEMPLO:
┌─────────────────────────────────────────────────┐
│ def test_user_registration_flow():              │
│     # Test integración con base de datos        │
│     user_service = UserService(real_db)         │
│     email_service = EmailService(mock_smtp)     │
│                                                 │
│     result = user_service.register(             │
│         email="test@example.com",               │
│         password="securepass123"                │
│     )                                           │
│                                                 │
│     assert result.success == True               │
│     assert email_service.sent_count == 1        │
│     assert db.users.find_by_email(...) != None  │
└─────────────────────────────────────────────────┘

SCOPE:
├── API → Base de datos
├── Servicio A → Servicio B
├── Frontend → Backend
└── App → Servicios externos

Tests End-to-End (E2E)

TESTS END-TO-END
════════════════

PROPÓSITO:
├── Simular usuario real
├── Verificar journeys completos
├── Encontrar bugs de integración
└── Validar UX crítica

EJEMPLO (Playwright):
┌─────────────────────────────────────────────────┐
│ test('usuario puede completar compra', async   │
│ ({ page }) => {                                 │
│   await page.goto('/products')                  │
│   await page.click('[data-product="widget"]')  │
│   await page.click('#add-to-cart')             │
│   await page.click('#checkout')                 │
│   await page.fill('#email', 'test@test.com')   │
│   await page.fill('#card', '4242424242424242') │
│   await page.click('#submit-order')            │
│                                                 │
│   await expect(page.locator('.success'))       │
│     .toContainText('Order confirmed')          │
│ })                                              │
└─────────────────────────────────────────────────┘

HERRAMIENTAS:
├── Playwright (recomendado)
├── Cypress
├── Selenium
└── Puppeteer

COBERTURA: Journeys críticos de negocio

Tests de API

TESTS DE API
════════════

PROPÓSITO:
├── Validar contratos de servicios
├── Verificar respuestas y códigos de estado
├── Probar autenticación/autorización
└── Performance básica de endpoints

EJEMPLO:
┌─────────────────────────────────────────────────┐
│ def test_create_user_endpoint():                │
│     response = client.post('/api/users', json={ │
│         "email": "new@user.com",                │
│         "name": "Test User"                     │
│     })                                          │
│                                                 │
│     assert response.status_code == 201          │
│     assert response.json()["id"] is not None   │
│     assert response.json()["email"] == ...     │
└─────────────────────────────────────────────────┘

VALIDACIONES:
├── Status codes (200, 201, 400, 401, 404, 500)
├── Response schema
├── Headers (Content-Type, Auth)
├── Error handling
└── Rate limiting

Integración con CI/CD

PIPELINE DE CI/CD CON TESTS
═══════════════════════════

┌─────────────────────────────────────────────────────────────┐
│                     PIPELINE CI/CD                          │
│                                                             │
│ ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐        │
│ │  Push   │→ │  Build  │→ │  Test   │→ │ Deploy  │        │
│ │  Code   │  │         │  │         │  │         │        │
│ └─────────┘  └─────────┘  └─────────┘  └─────────┘        │
│                              │                              │
│                              ▼                              │
│              ┌───────────────────────────────┐             │
│              │        STAGE: TEST            │             │
│              │                               │             │
│              │ 1. Unit Tests (paralelo)      │             │
│              │    └── 2-3 minutos            │             │
│              │                               │             │
│              │ 2. Integration Tests          │             │
│              │    └── 5-10 minutos           │             │
│              │                               │             │
│              │ 3. E2E Tests (críticos)       │             │
│              │    └── 10-15 minutos          │             │
│              │                               │             │
│              │ 4. Cobertura y Reportes       │             │
│              │    └── Upload a GitScrum      │             │
│              └───────────────────────────────┘             │
│                                                             │
│              Si falla cualquier stage → Pipeline falla     │
└─────────────────────────────────────────────────────────────┘

Configuración GitHub Actions

# .github/workflows/test.yml
EJEMPLO DE WORKFLOW:
═══════════════════

name: Tests
on: [push, pull_request]

jobs:
  unit-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run Unit Tests
        run: pytest tests/unit --cov=src
      - name: Upload Coverage
        uses: codecov/codecov-action@v3

  integration-tests:
    needs: unit-tests
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15
    steps:
      - uses: actions/checkout@v4
      - name: Run Integration Tests
        run: pytest tests/integration

  e2e-tests:
    needs: integration-tests
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run E2E Tests
        run: npx playwright test

Métricas de Testing

DASHBOARD DE MÉTRICAS DE TESTING
════════════════════════════════

COBERTURA DE CÓDIGO:
┌─────────────────────────────────────────┐
│ Líneas:      ████████░░ 82%             │
│ Branches:    ███████░░░ 75%             │
│ Funciones:   █████████░ 89%             │
│ Statements:  ████████░░ 81%             │
│                                         │
│ Meta: >80%   Estado: ✅ Cumplida        │
└─────────────────────────────────────────┘

RESULTADOS DE TESTS:
┌─────────────────────────────────────────┐
│ Total: 1,247 tests                      │
│ ✅ Pasaron: 1,239 (99.4%)               │
│ ❌ Fallaron: 5 (0.4%)                   │
│ ⏭️ Skipped: 3 (0.2%)                    │
│                                         │
│ Tiempo: 4m 32s                          │
└─────────────────────────────────────────┘

TENDENCIA (últimos 30 días):
┌─────────────────────────────────────────┐
│ Cobertura: ↑ +3% (79% → 82%)           │
│ Tests fallando: ↓ -8 (13 → 5)          │
│ Tiempo ejecución: ↓ -45s (5m17s → 4m32s)│
│ Tests flaky: ↓ -2 (4 → 2)              │
└─────────────────────────────────────────┘

Mejores Prácticas

MEJORES PRÁCTICAS DE TESTING
════════════════════════════

✓ Sigue la pirámide de testing
  └── Más unitarios, menos E2E

✓ Tests deben ser independientes
  └── Orden de ejecución no importa

✓ Tests deben ser determinísticos
  └── Mismo resultado cada vez

✓ Nombra tests descriptivamente
  └── test_user_with_expired_token_gets_401

✓ Un assert por test (idealmente)
  └── Fácil identificar qué falló

✓ Ejecuta tests antes de merge
  └── Gate de calidad obligatorio

✓ Arregla tests flaky inmediatamente
  └── Erosionan confianza

Anti-Patrones

ANTI-PATRONES DE TESTING
════════════════════════

✗ Pirámide invertida (muchos E2E, pocos unit)
  └── Tests lentos y frágiles

✗ Tests que dependen de orden
  └── Fallan aleatoriamente

✗ Tests que acceden a producción
  └── Datos reales = problemas

✗ Ignorar tests fallando
  └── "Siempre falla, ignóralo"

✗ 100% cobertura a cualquier costo
  └── Tests sin valor real

✗ Tests sin assertions
  └── Solo verifican que no crashea

Soluciones Relacionadas