typestar

Probar errores en Go

Aserta sobre el centinela o el tipo, nunca sobre el texto del mensaje.

var ErrBadStars = errors.New("stars out of range")

func Validate(stars int) error {
    if stars < 0 || stars > 3 {
        return fmt.Errorf("validate %d: %w", stars, ErrBadStars)
    }
    return nil
}

func TestValidate(t *testing.T) {
    cases := []struct {
        stars   int
        wantErr error
    }{
        {2, nil},
        {9, ErrBadStars},
    }

    for _, c := range cases {
        err := Validate(c.stars)
        if !errors.Is(err, c.wantErr) {
            t.Errorf("Validate(%d) = %v, want %v", c.stars, err, c.wantErr)
        }
    }
}

Cómo funciona

  1. errors.Is es la comparación correcta para un error envuelto.
  2. Un campo wantErr en la tabla cubre ambos caminos.
  3. Comparar err.Error() se rompe en cuanto agregas contexto.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
25
Caracteres a escribir
452
Tokens
124
Ritmo de tres estrellas
100 tpm

Al ritmo de tres estrellas de 100 tokens por minuto, este intento toma unos 74 segundos.

Escribe este fragmento

Paso 4 de 4 en Escribir pruebas; paso 4 de 13 en Pruebas.

← Anterior Siguiente →