Spec Sistemas Com Go • Trilha Progressiva em 4 Níveis


🧭 Navegação Pedagógica


🎯 Nível 1: Fundamentos

Problema 18.1 — Teste Unitário Simples com o Pacote testing (*testing.T)

Contexto: Teste Unitário Simples com o Pacote testing (*testing.T) no contexto de Testes Automatizados: testing, Table-Driven Tests e Benchmarks.

Requisitos de Execução:

  1. Criar arquivo calculadora_test.go com função TestSomar(t *testing.T).

Resultado Esperado

Teste unitário executado e aprovado via `go test`.

📤 Instruções de Entrega (Microsoft Teams)

  1. Salve o arquivo como: Atividade_18_1_SeuNome
  2. Envie na tarefa: Atividade Cap 18 - Testes Automatizados: testing, Table-Driven Tests e Benchmarks
🔑 Gabarito de Código & Solução Comentada
package main

import "testing"

func Somar(a, b int) int { return a + b }

func TestSomar(t *testing.T) {
    if obtido := Somar(2, 3); obtido != 5 {
        t.Errorf("Esperado 5, obtido %d", obtido)
    }
}

🔍 Nível 2: Prática

Problema 18.2 — Table-Driven Tests Idiomáticos com t.Run()

Contexto: Table-Driven Tests Idiomáticos com t.Run() no contexto de Testes Automatizados: testing, Table-Driven Tests e Benchmarks.

Requisitos de Execução:

  1. Estruturar testes com matriz de structs anônimas executando subtestes nomeados.

Resultado Esperado

Matriz de testes table-driven executada com cobertura de casos de borda.

📤 Instruções de Entrega (Microsoft Teams)

  1. Salve o arquivo como: Atividade_18_2_SeuNome
  2. Envie na tarefa: Atividade Cap 18 - Testes Automatizados: testing, Table-Driven Tests e Benchmarks
🔑 Gabarito de Código & Solução Comentada
package main

import "testing"

func TestParidade(t *testing.T) {
    testes := []struct {
        nome string
        num  int
        esperado bool
    }{
        {"Par", 4, true},
        {"Impar", 7, false},
        {"Zero", 0, true},
    }

    for _, tt := range testes {
        t.Run(tt.nome, func(t *testing.T) {
            if (tt.num%2 == 0) != tt.esperado {
                t.Fail()
            }
        })
    }
}

⚡ Nível 3: Integração

Problema 18.3 — Benchmarks de Performance com *testing.B e b.ResetTimer()

Contexto: Benchmarks de Performance com *testing.B e b.ResetTimer() no contexto de Testes Automatizados: testing, Table-Driven Tests e Benchmarks.

Requisitos de Execução:

  1. Escrever função de benchmark BenchmarkProcessamento(b *testing.B) medindo nanossegundos por operação (ns/op).

Resultado Esperado

Benchmark executado via `go test -bench=. -benchmem`.

📤 Instruções de Entrega (Microsoft Teams)

  1. Salve o arquivo como: Atividade_18_3_SeuNome
  2. Envie na tarefa: Atividade Cap 18 - Testes Automatizados: testing, Table-Driven Tests e Benchmarks
🔑 Gabarito de Código & Solução Comentada
package main

import "testing"

func BenchmarkLoop(b *testing.B) {
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        _ = i * 2
    }
}

🏆 Nível 4: Desafio Corporativo

Problema 18.4 — Análise de Cobertura de Código (Coverage) com go test -coverprofile

Contexto: Análise de Cobertura de Código (Coverage) com go test -coverprofile no contexto de Testes Automatizados: testing, Table-Driven Tests e Benchmarks.

Requisitos de Execução:

  1. Gerar relatório visual de cobertura HTML com go tool cover -html=coverage.out.

Resultado Esperado

Cobertura de código medida com 100% de branching coberto.

📤 Instruções de Entrega (Microsoft Teams)

  1. Salve o arquivo como: Atividade_18_4_SeuNome
  2. Envie na tarefa: Atividade Cap 18 - Testes Automatizados: testing, Table-Driven Tests e Benchmarks
🔑 Gabarito de Código & Solução Comentada
package main

import (
    "fmt"
    "os/exec"
)

func ExecutarAuditoriaCobertura() error {
    cmd := exec.Command("go", "test", "-v", "-coverprofile=coverage.out", "./...")
    out, err := cmd.CombinedOutput()
    if err != nil { return err }
    fmt.Printf("Relatorio de Cobertura Go gerado com sucesso: %s\n", string(out))
    return nil
}

⬅️ Voltar ao Índice de Exercícios 📚 Sumário de Tópicos