miércoles, 1 de noviembre de 2023

Test en Go


Go ofrece soporte integrado para pruebas unitarias que hace que sea más fácil realizar pruebas sobre la marcha. Específicamente, utilizando las convenciones de nomenclatura, el paquete de pruebas de Go y el comando go test, puede escribir y ejecutar pruebas rápidamente.

Veamos un ejemplo, vamos a hacer un archivo greetings con el siguiente contenido : 

package greetings


import "fmt"


// Hello returns a greeting for the named person.

func Hello(name string) (message string) {

// Return a greeting that embeds the name in a message.

if name == "" {

message = "Hi!"

} else {

message = fmt.Sprintf("Hi, %v. Welcome!", name)

}

return message

}


En el directorio greetings, crearemos un archivo llamado greetings_test.go, que son las pruebas. Terminar el nombre de un archivo con _test.go le indica al comando go test que este archivo contiene test.

En Greetings_test.go, vamos a pegar el siguiente código y guardar el archivo.

package greetings


import (

"regexp"

"testing"

)


// TestHelloName calls greetings.Hello with a name, checking

// for a valid return value.

func TestHelloName(t *testing.T) {

name := "Gladys"

want := regexp.MustCompile(`\b` + name + `\b`)

msg := Hello("Gladys")

if !want.MatchString(msg) {

t.Fatalf(`Hello("Gladys") = %q, %v`, msg, want)

}

}


// TestHelloEmpty calls greetings.Hello with an empty string.

func TestHelloEmpty(t *testing.T) {

msg := Hello("")

if msg != "Hi!" {

t.Fatalf(`Hello("") = %q, want "Hi!"`, msg)

}

}


En este código, se puede ver que utilizamos el paquete "test" para hacer uso de función "Fatalf"  que indica que la función no pasa el test. 

Si ejecutamos go test en el directorio obtendremos : 

$ go test

PASS

ok      example.com/greetings   0.364s


$ go test -v

=== RUN   TestHelloName

--- PASS: TestHelloName (0.00s)

=== RUN   TestHelloEmpty

--- PASS: TestHelloEmpty (0.00s)

PASS

ok      example.com/greetings   0.372s


Y eso es todo! 

Dejo link : https://go.dev/doc/tutorial/add-a-test




No hay comentarios.:

Publicar un comentario