Le package testing
Go a le testing intégré dans le langage. Pas besoin d'installer Jest, pytest ou PHPUnit. Tout est déjà là.
Règles simples :
- Le fichier de test s'appelle
*_test.go(ex :math_test.go) - Les fonctions de test commencent par
Test(majuscule) - Elles prennent un paramètre
*testing.T
En Go, comment l'outil go test sait-il qu'une fonction est un test ? Faut-il une annotation ou un décorateur comme dans d'autres langages ? Avant de dérouler : quelle différence entre t.Error et t.Fatal dans un test ?
Voir la réponse
Il n'y a aucune annotation ni décorateur en Go. go test repère les tests par convention : une fonction de test doit s'appeler TestXxx (le mot Test suivi d'un nom commençant par une majuscule) et prendre un unique paramètre t *testing.T, dans un fichier dont le nom se termine par _test.go. Le nom et la signature suffisent, l'outil les découvre automatiquement. Pour signaler un échec : t.Error (ou t.Errorf) marque le test comme échoué mais continue l'exécution du reste de la fonction ; t.Fatal (ou t.Fatalf) marque l'échec et stoppe immédiatement la fonction de test, utile quand la suite n'a plus de sens (par exemple après une erreur d'initialisation).
// math.go
package math
func Add(a, b int) int {
return a + b
}
// math_test.go
package math
import "testing"
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d, attendu 5", result)
}
}
Lancez les tests avec go test :
$ go test
PASS
ok myproject/math 0.002s
0.002 secondes. Pas de setup, pas de configuration, pas de dépendances. Juste go test.
Table-driven tests : l'idiome Go
Les table-driven tests sont le pattern le plus utilisé en Go. Au lieu d'écrire une fonction par cas de test, vous définissez un tableau de cas :
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positifs", 2, 3, 5},
{"négatifs", -1, -2, -3},
{"zéro", 0, 0, 0},
{"mixte", -5, 10, 5},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Add(tt.a, tt.b)
if result != tt.expected {
t.Errorf("Add(%d, %d) = %d, attendu %d",
tt.a, tt.b, result, tt.expected)
}
})
}
}
Chaque cas de test a un nom : quand un test échoue, vous savez immédiatement lequel. Et ajouter un nouveau cas ? Une seule ligne.
Sortie avec go test -v :
=== RUN TestAdd
=== RUN TestAdd/positifs
=== RUN TestAdd/négatifs
=== RUN TestAdd/zéro
=== RUN TestAdd/mixte
--- PASS: TestAdd (0.00s)
--- PASS: TestAdd/positifs (0.00s)
--- PASS: TestAdd/négatifs (0.00s)
--- PASS: TestAdd/zéro (0.00s)
--- PASS: TestAdd/mixte (0.00s)
PASS
ok myproject/math 0.002s
Benchmarks : mesurer les performances
Go intègre aussi les benchmarks. Même fichier _test.go, mais avec Benchmark au lieu de Test. Mesurons une fonction qui fait un vrai travail, un Fibonacci récursif :
// fib.go
package fib
func Fib(n int) int {
if n < 2 {
return n
}
return Fib(n-1) + Fib(n-2)
}
// fib_test.go
package fib
import "testing"
var sink int // consume the result so the call cannot be dropped
func BenchmarkFib(b *testing.B) {
for i := 0; i < b.N; i++ {
sink = Fib(20)
}
}
Lancez avec go test -bench=. :
$ go test -bench=.
BenchmarkFib-24 50934 23420 ns/op
PASS
ok myproject/fib 1.437s
Go a répété la fonction environ 51 000 fois et chaque appel a pris environ 23 microsecondes (ns/op = nanosecondes par opération). Ces chiffres changent d'une machine à l'autre (le -24 est le nombre de cœurs utilisables sur celle-ci) : l'intérêt est de comparer avant et après une modification, avec des chiffres plutôt que des intuitions.
Vous pouvez aussi mesurer la mémoire avec -benchmem :
$ go test -bench=. -benchmem
BenchmarkFib-24 51170 23524 ns/op 0 B/op 0 allocs/op
PASS
ok myproject/fib 1.447s
0 B/op et 0 allocs/op : aucune allocation mémoire par opération, car Fib n'utilise que la pile. Une fonction qui construit des slices ou des chaînes peut afficher des valeurs non nulles, et ce sont elles qu'on cherche à faire baisser.
Le piège du micro-benchmark. Faites la même mesure sur Add(2, 3) : vous obtiendrez de l'ordre de 0,2 ns par opération (0,207 ns mesurés ici), avec ou sans variable de package pour le résultat. Ce n'est pas la vitesse de l'addition, c'est le coût de la boucle seule : le compilateur inline l'appel et calcule même 5 à la compilation (visible dans l'assembleur avec go test -c -gcflags=-S). Un benchmark n'a de sens que sur du travail réel, dont le résultat est consommé (d'où sink ci-dessus). Depuis Go 1.24, la forme recommandée est for b.Loop() { … } plutôt que la boucle b.N.
Commandes utiles
# Lancer tous les tests
go test ./...
# Tests avec détails
go test -v ./...
# Couverture de code
go test -cover ./...
# Générer un rapport de couverture
go test -coverprofile=cover.out ./...
go tool cover -html=cover.out
# Benchmarks
go test -bench=. -benchmem ./...
go test ./... lance les tests dans tous les packages de votre projet. Le -cover vous montre quel pourcentage de votre code est couvert par les tests.
À vous : voici un vrai test, lancé par go test dans le bac à sable de cette page. La table de cas est déjà écrite, mais la fonction Abs a un bug. Trois étapes :
- Exécutez : le test échoue (rouge) et indique quel cas, avec la valeur obtenue et la valeur attendue.
- Corrigez
Abs(le bug est dans la fonction, pas dans le test), puis exécutez à nouveau :PASS. - Ajoutez un cas à la table, par exemple
{"grand négatif", -1000, 1000}, et vérifiez qu'il passe aussi.
package main
import "testing"
// Abs renvoie la valeur absolue de n.
func Abs(n int) int {
if n < 0 {
return n
}
return n
}
func TestAbs(t *testing.T) {
tests := []struct {
name string
n int
expected int
}{
{"positif", 3, 3},
{"négatif", -3, 3},
{"zéro", 0, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Abs(tt.n)
if result != tt.expected {
t.Errorf("Abs(%d) = %d, attendu %d", tt.n, result, tt.expected)
}
})
}
}
Le bac à sable lance go test sans l'option -v : on n'y voit que les échecs et la ligne finale ok. Pour le détail de chaque sous-test, lancez go test -v chez vous.
Voir la solution
Pour un nombre négatif, Abs renvoyait n tel quel. Il faut renvoyer -n :
func Abs(n int) int {
if n < 0 {
return -n
}
return n
}
The testing package
Go has testing built into the language. No need to install Jest, pytest, or PHPUnit. Everything is already there.
Simple rules:
- Test files are named
*_test.go(e.g.,math_test.go) - Test functions start with
Test(capital T) - They take a
*testing.Tparameter
In Go, how does go test know a function is a test? Is there an annotation or decorator to add, like in other languages? Before scrolling: what is the difference between t.Error and t.Fatal in a test?
See the answer
There is no annotation or decorator in Go. go test finds tests by convention: a test function must be named TestXxx (the word Test followed by a name starting with a capital letter) and take a single parameter t *testing.T, inside a file whose name ends with _test.go. The name and signature are enough; the tool discovers them automatically. To signal a failure: t.Error (or t.Errorf) marks the test as failed but continues executing the rest of the test function; t.Fatal (or t.Fatalf) marks the failure and stops the test function immediately, useful when the rest makes no sense (for example after an initialization error).
// math.go
package math
func Add(a, b int) int {
return a + b
}
// math_test.go
package math
import "testing"
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d, expected 5", result)
}
}
Run tests with go test:
$ go test
PASS
ok myproject/math 0.002s
0.002 seconds. No setup, no configuration, no dependencies. Just go test.
Table-driven tests — the Go idiom
Table-driven tests are the most common pattern in Go. Instead of writing one function per test case, you define a table of cases:
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positives", 2, 3, 5},
{"negatives", -1, -2, -3},
{"zeros", 0, 0, 0},
{"mixed", -5, 10, 5},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Add(tt.a, tt.b)
if result != tt.expected {
t.Errorf("Add(%d, %d) = %d, expected %d",
tt.a, tt.b, result, tt.expected)
}
})
}
}
Each test case has a name — when a test fails, you immediately know which one. And adding a new case? Just one line.
Output with go test -v:
=== RUN TestAdd
=== RUN TestAdd/positives
=== RUN TestAdd/negatives
=== RUN TestAdd/zeros
=== RUN TestAdd/mixed
--- PASS: TestAdd (0.00s)
--- PASS: TestAdd/positives (0.00s)
--- PASS: TestAdd/negatives (0.00s)
--- PASS: TestAdd/zeros (0.00s)
--- PASS: TestAdd/mixed (0.00s)
PASS
ok myproject/math 0.002s
Benchmarks: measuring performance
Go also has built-in benchmarks. Same _test.go file, but with Benchmark instead of Test. Let's measure a function that does real work, a recursive Fibonacci:
// fib.go
package fib
func Fib(n int) int {
if n < 2 {
return n
}
return Fib(n-1) + Fib(n-2)
}
// fib_test.go
package fib
import "testing"
var sink int // consume the result so the call cannot be dropped
func BenchmarkFib(b *testing.B) {
for i := 0; i < b.N; i++ {
sink = Fib(20)
}
}
Run with go test -bench=.:
$ go test -bench=.
BenchmarkFib-24 50934 23420 ns/op
PASS
ok myproject/fib 1.437s
Go repeated the function about 51,000 times and each call took about 23 microseconds (ns/op = nanoseconds per operation). These numbers change from one machine to another (the -24 is the number of usable cores on this one): the point is to compare before and after a change, with numbers rather than intuition.
You can also measure memory with -benchmem:
$ go test -bench=. -benchmem
BenchmarkFib-24 51170 23524 ns/op 0 B/op 0 allocs/op
PASS
ok myproject/fib 1.447s
0 B/op and 0 allocs/op: no memory allocation per operation, because Fib only uses the stack. A function that builds slices or strings may show non-zero values, and those are the ones you try to bring down.
Watch out for the micro-benchmark trap. Run the same measurement on Add(2, 3) and you get about 0.2 ns per operation (0.207 ns measured here), with or without a package-level variable for the result. That is not the speed of the addition, it is the cost of the bare loop: the compiler inlines the call and even computes 5 at compile time (visible in the assembly with go test -c -gcflags=-S). A benchmark only makes sense on real work whose result is consumed (hence sink above). Since Go 1.24, the recommended form is for b.Loop() { … } rather than the b.N loop.
Useful commands
# Run all tests
go test ./...
# Tests with details
go test -v ./...
# Code coverage
go test -cover ./...
# Generate coverage report
go test -coverprofile=cover.out ./...
go tool cover -html=cover.out
# Benchmarks
go test -bench=. -benchmem ./...
go test ./... runs tests in all packages of your project. The -cover flag shows what percentage of your code is covered by tests.
Your turn: here is a real test, run by go test in this page's sandbox. The table of cases is already written, but the Abs function has a bug. Three steps:
- Run it: the test fails (red) and tells you which case, with the actual and the expected value.
- Fix
Abs(the bug is in the function, not in the test), then run it again:PASS. - Add a case to the table, for example
{"large negative", -1000, 1000}, and check that it passes too.
package main
import "testing"
// Abs returns the absolute value of n.
func Abs(n int) int {
if n < 0 {
return n
}
return n
}
func TestAbs(t *testing.T) {
tests := []struct {
name string
n int
expected int
}{
{"positive", 3, 3},
{"negative", -3, 3},
{"zero", 0, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Abs(tt.n)
if result != tt.expected {
t.Errorf("Abs(%d) = %d, expected %d", tt.n, result, tt.expected)
}
})
}
}
The sandbox runs go test without the -v flag: you only see failures and the final ok line. For the detail of each subtest, run go test -v on your machine.
Show the solution
For a negative number, Abs returned n unchanged. It must return -n:
func Abs(n int) int {
if n < 0 {
return -n
}
return n
}
🎯 Pratique
S'entraîner (clique pour ouvrir) :
✨ Prompt IA
Copiez ce prompt dans Claude ou ChatGPT :
Écris des table-driven tests Go pour une fonction qui valide une adresse email. Teste les cas valides, invalides, vides et les cas limites. Ajoute un benchmark.
💬 Ré-explique sans regarder
Sans relire le code de l'IA : expliquez avec vos mots comment un table-driven test est structuré et pourquoi on nomme chaque cas via t.Run(tt.name, ...).
for _, tt := range tests. À l'intérieur, t.Run(tt.name, ...) crée un sous-test nommé : si un cas échoue, la sortie indique précisément lequel (ex : TestAdd/négatifs), et on peut relancer un seul cas. Ajouter un cas = ajouter une ligne au tableau.⚖️ Juge le code de l'IA
Vous avez demandé à l'IA un test pour une fonction Divide(a, b int) (int, error). Voici ce qu'elle propose. Votre rôle de relecteur : l'accepter tel quel ou le rejeter, et dire pourquoi.
func TestDivide(t *testing.T) {
result, _ := Divide(10, 0)
if result != 0 {
t.Errorf("Divide(10, 0) = %d, attendu 0", result)
}
}
_ : pour une division par zéro, c'est justement l'error qu'on veut vérifier, pas la valeur de retour. Tel quel, le test passe même si Divide ne renvoie jamais d'erreur, donc il ne teste rien d'utile. Le bon réflexe : capturer l'erreur (result, err := Divide(10, 0)) et asserter if err == nil { t.Error("attendu une erreur pour la division par zéro") }.🧠 Rappel libre
Sans remonter dans la leçon : comment doit s'appeler un fichier de test en Go, et quelle commande lance les benchmarks (avec les allocations mémoire) ?
_test.go (ex : math_test.go) ; le suffixe _test est obligatoire pour que go test le détecte. Pour les benchmarks avec la mémoire : go test -bench=. -benchmem (le . signifie « tous les benchmarks », -benchmem ajoute les colonnes B/op et allocs/op).Pour aller plus loin
Vous maîtrisez maintenant les fondamentaux de Go. Voici les sujets avancés à explorer ensuite :
- Erreurs enveloppées :
%w,errors.Iseterrors.AsWorking with errors - Tester une API :
httptestsimule des requêtes sans lancer de serveur httptest - Modules :
go.modpour gérer les dépendances Tutorial - Gin / Echo : frameworks web populaires pour les API Gin · Echo
- GORM : un ORM populaire en Go gorm.io
Références complètes : Go.dev Documentation · A Tour of Go · Go by Example
Vous êtes un développeur polyvalent
Go est le langage de l'infrastructure moderne. Performant, simple, conçu pour le cloud. Avec HTML/CSS/JS pour le front, PHP ou Python pour le back, et Go pour les services haute performance, vous avez une palette complète de développeur polyvalent.
Vous n'êtes plus un débutant : vous êtes un développeur qui utilise l'IA comme un outil, pas comme une béquille.
En 11 leçons, vous avez parcouru les variables, les conditions et boucles, les slices et maps, les fonctions et erreurs, les méthodes et interfaces, les génériques, la concurrence, les API REST et les tests. Vous avez les bases pour construire des services rapides et fiables.
La suite ? Construisez quelque chose. Un CLI, une API, un microservice. Le meilleur apprentissage, c'est la pratique.
Going further
You now master Go's fundamentals. Here are advanced topics to explore next:
- Wrapped errors:
%w,errors.Isanderrors.AsWorking with errors - Testing an API:
httptestsimulates requests without starting a server httptest - Modules —
go.modfor dependency management Tutorial - Gin / Echo — popular web frameworks for APIs Gin · Echo
- GORM — a popular ORM in Go gorm.io
Full references: Go.dev Documentation · A Tour of Go · Go by Example
You are a versatile developer
Go is the language of modern infrastructure. Performant, simple, designed for the cloud. With HTML/CSS/JS for the front, PHP or Python for the back, and Go for high-performance services, you have a complete versatile developer toolkit.
You're no longer a beginner — you're a developer who uses AI as a tool, not as a crutch.
In 11 lessons, you went through variables, conditions and loops, slices and maps, functions and errors, methods and interfaces, generics, concurrency, REST APIs, and testing. You have the foundation to build fast and reliable services.
What's next? Build something. A CLI, an API, a microservice. The best learning is practice.
You now know Go end to end: variables, errors, concurrency, APIs and tests. The best way to make it stick is to build something real. Head to the projects to put Go into practice on a concrete case.
Move on to projects →