Testes em Go (Golang): frameworks e ferramentas

Treinador Online de Python para Iniciantes

Aprenda Python facilmente sem sobrecarga teórica. Resolva tarefas práticas com verificação automática e escreva código diretamente no navegador.

Start Course

Testes em Go (Golang): frameworks e ferramentas



Go (Golang) foi projetado desde o início com as necessidades do desenvolvimento moderno em mente, portanto, a biblioteca padrão já possui um pacote poderoso testing. No entanto, para projetos complexos, geralmente são necessárias ferramentas adicionais: mocks, assertions, estilo BDD e verificação de vazamento de goroutines. Neste artigo, vamos analisar os principais frameworks e bibliotecas para testes em Go, mostrar exemplos de código e explicar quando usar cada um.



1. Pacote embutido testing



O pacote padrão testing é a base de tudo. Os testes são escritos em arquivos com o sufixo _test.go, e as funções devem ter a assinatura func TestXxx(t *testing.T). Exemplo:



package main

import ( "testing")

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

func TestSum(t *testing.T) { result := Sum(2, 3) expected := 5 if result != expected { t.Errorf("Sum(2,3) = %d; want %d", result, expected) }}


Execução dos testes: go test ./.... Para benchmarks, usa-se testing.B, para exemplos — ExampleXxx.



2. Biblioteca testify



Testify é a biblioteca de terceiros mais popular para testes em Go. Ela fornece assertions convenientes, mocks e funções auxiliares.



Instalação:

go get github.com/stretchr/testify


Exemplo com assertions:

package main

import ( "testing" "github.com/stretchr/testify/assert")

func TestSumWithTestify(t *testing.T) { result := Sum(2, 3) assert.Equal(t, 5, result, "Sum should be 5") assert.NotEqual(t, 0, result) assert.True(t, result > 0)}


Testify também inclui o pacote mock para criar mocks. Exemplo:

package main

import ( "testing" "github.com/stretchr/testify/mock")

// DataService — interface que vamos mockartype DataService interface { GetData(id int) string}

// MockDataService — estrutura mocktype MockDataService struct { mock.Mock}

func (m *MockDataService) GetData(id int) string { args := m.Called(id) return args.String(0)}

func TestGetData(t *testing.T) { mockService := new(MockDataService) mockService.On("GetData", 1).Return("result1")

result := mockService.GetData(1) assert.Equal(t, "result1", result) mockService.AssertExpectations(t)}


3. gomock — geração de mocks



Gomock do Google é um framework para gerar mocks baseados em interfaces. Funciona através da utilidade mockgen.



Instalação:

go install github.com/golang/mock/mockgen@v1.6.0


Exemplo de uso:

//go:generate mockgen -source=service.go -destination=mock_service.go -package=main

type Service interface { Process(data string) error}

// No teste:func TestProcess(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish()

mockService := NewMockService(ctrl) mockService.EXPECT().Process("test").Return(nil)

err := mockService.Process("test") assert.NoError(t, err)}


Gomock é bom para projetos grandes, onde há muitas interfaces — a geração de código economiza tempo.



4. ginkgo — estilo BDD



Ginkgo é um framework para Behaviour-Driven Development (BDD). Permite escrever testes no estilo "Describe", "Context" e "It".



Instalação:

go get github.com/onsi/ginkgo/v2go get github.com/onsi/gomega


Exemplo:

package main

import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "testing")

func TestCalculator(

Recommendations