Bastante interesante la forma de manejar los tests con el slice de structs
Introducción
CaracterÃsticas esenciales de Go
Qué aprenderás y qué necesitas saber
Repaso general: variables, condicionales, slices y map
Repaso general: GoRoutines y apuntadores
Programación orientada a objetos
¿Es Go orientado a objetos?
Structs vs. clases
Métodos y funciones
Constructores
Herencia
Interfaces
Aplicando interfaces con Abstract Factory
Implementación final de Abstract Factory
Funciones anónimas
Funciones variadicas y retornos con nombre
Go Modules
Cómo utilizar los Go modules
Creando nuestro módulo
Testing
Testing
Code coverage
Profiling
Testing usando Mocks
Implementando Mocks
Concurrencia
Unbuffered channels y buffered channels
Waitgroup
Buffered channels como semáforos
Definiendo channels de lectura y escritura
Worker pools
Multiplexación con Select y Case
Proyecto: servidor con worker pools
Definiendo workers, jobs y dispatchers
Creando web server para procesar jobs
Conclusión
Continúa con el Curso de Go Avanzado
Aún no tienes acceso a esta clase
Crea una cuenta y continúa viendo este curso
Aportes 8
Preguntas 2
Bastante interesante la forma de manejar los tests con el slice de structs
Testing
Go has a builtin testing library, which is awesome!
To define a test must:
<file>_test.go
, where <file>
is the name of the file you are testinggo test
main.go:
package main
func Sum(x, y int) int {
return x + y
}
main_test.go:
package main
import (
"fmt"
"testing"
)
func TestSum(t *testing.T) {
fmt.Println()
total := Sum(5, 5)
if total != 10 {
t.Errorf("Wrong output, expected 10, go %d", total)
}
}
Often times it’s useful to test various cases in single test. To do that you’d wanna use a slice and iterate over them like so:
tableCases := []struct {
a int
b int
n int
}{
{1, 2, 3},
{2, 2, 4},
{25, 26, 51},
}
for _, item := range tableCases {
total := Sum(item.a, item.b)
if total != item.n {
t.Errorf("Failed: Incorrect sum, got %d expected %d", total, item.n)
}
}
main_test
package main
import "testing"
func TestSum(t *testing.T) {
tables := []struct {
x int
y int
r int
}{
{1, 2, 3},
{2, 2, 4},
{3, 2, 5},
{25, 26, 51},
}
for _, table := range tables {
total := Sum(table.x, table.y)
if total != table.r {
t.Errorf("Sum(%d, %d) was incorrect, got: %d, want: %d.", table.x, table.y, total, table.r)
}
}
}
main
package main
func Sum(x, y int) int {
return x + y
}
func GetMax(x, y int) int {
if x > y {
return x
}
return y
}
Para programar los tests os recomiendo utilizar el módulo https://github.com/stretchr/testify, ya que te ofrece diversas funcionalidades que facilitan la vida a la hora de programar los tests de Go.
Yo encuentro especialmente útil el paquete assert, el qual te permite hacer los asserts igual que en cualquier lenguaje de programación. Por ejempo:
assert.Equal(t, 63997.93, newImport)
main.go
package main
import (
"fmt"
"strings"
)
func Sum(x, y int) int {
return x + y
}
func SayHello(name string) string {
return fmt.Sprintf("Hello %v", strings.Title(strings.ToLower(name)))
}
func GreaterThan(x, y int) int {
if x > y {
return x
}
return y
}
func SumTotal(numbers ...int) int {
total := 0
for _, val := range numbers {
total += val
}
return total
}
main_test.go
package main
import (
"testing"
)
func TestSum(t *testing.T) {
type args struct {
x int
y int
}
tests := []struct {
name string
args args
want int
}{
// TODO: Add test cases.
{name: "Test Sum Correct", args: args{x: 6, y: 6}, want: 12},
{name: "Test Sum Correct", args: args{x: 5, y: 5}, want: 10},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Sum(tt.args.x, tt.args.y); got != tt.want {
t.Errorf("Sum() = %v, want %v", got, tt.want)
}
})
}
}
func TestSayHello(t *testing.T) {
type args struct {
name string
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
{name: "Correctly", args: args{name: "pedro"}, want: "Hello Pedro"},
{name: "Correctly", args: args{name: "Ramon"}, want: "Hello Ramon"},
{name: "Correctly", args: args{name: "mARIa"}, want: "Hello Maria"},
{name: "Correctly", args: args{name: "DIANA"}, want: "Hello Diana"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := SayHello(tt.args.name); got != tt.want {
t.Errorf("SayHello() = %v, want %v", got, tt.want)
}
})
}
}
func TestGreaterThan(t *testing.T) {
type args struct {
x int
y int
}
tests := []struct {
name string
args args
want int
}{
// TODO: Add test cases.
{name: "Equal", args: args{x: 6, y: 6}, want: 6},
{name: "X greater", args: args{x: 9, y: 8}, want: 9},
{name: "Y greater", args: args{x: 1, y: 99}, want: 99},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := GreaterThan(tt.args.x, tt.args.y); got != tt.want {
t.Errorf("GreaterThan() = %v, want %v", got, tt.want)
}
})
}
}
func TestSumTotal(t *testing.T) {
type args struct {
numbers []int
}
tests := []struct {
name string
args args
want int
}{
// TODO: Add test cases.
{name: "Correctly", args: args{[]int{1, 3, 2}}, want: 6},
{name: "Correctly", args: args{[]int{106, 105, 6}}, want: 217},
{name: "Correctly", args: args{[]int{96, 3, 0}}, want: 99},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := SumTotal(tt.args.numbers...); got != tt.want {
t.Errorf("SumTotal() = %v, want %v", got, tt.want)
}
})
}
}
El curso la verdad es excelente, super bien explicado y las testing y es la parte fundamental de un codigo de alta calidad
Interesante
Para correr los test en paralelo.
package main
import "testing"
// func TestSum(t *testing.T) {
// total := Sum(5, 5)
// if total != 10 {
// t.Error("Suma was incorrect, got ", total, "expected ", 10)
// }
// }
func TestSum(t *testing.T) {
t.Parallel()
testCases := []struct {
desc string
a, b, n int
}{
{
desc: "Tetsing 1+2 = 3",
a: 1, b: 2, n: 3,
},
{
desc: "Tetsing 2+2 = 4",
a: 2, b: 2, n: 4,
},
{
desc: "Tetsing 25+26 = 51",
a: 25, b: 26, n: 51,
},
}
for _, tC := range testCases {
tC := tC
t.Run(tC.desc, func(t *testing.T) {
t.Parallel()
total := Sum(tC.a, tC.b)
if total != tC.n {
t.Error("Sum was incorrect, got", total, "expected", tC.n)
}
})
}
}
¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.