Learn how to test your functions and ensure their correctness.
Unit tests ensure that each part of your code works correctly and prevents regressions during updates.
Go includes the built-in `testing` package for writing and executing unit tests.
package main
import (
"testing"
)
func Addition(a, b int) int {
return a + b
}
func TestAddition(t *testing.T) {
result := Addition(2, 3)
expected := 5
if result != expected {
t.Errorf("Incorrect result: got %d, expected %d", result, expected)
}
}
Tests can be executed with the command:
go test
maths.go
containing a function `Multiplication`.maths_test.go
to test this function.package main
import (
"testing"
)
func Multiplication(a, b int) int {
return a * b
}
func TestMultiplication(t *testing.T) {
result := Multiplication(4, 5)
expected := 20
if result != expected {
t.Errorf("Error: got %d, expected %d", result, expected)
}
}
📚 Learn more about testing in Go:
Read the Official Documentation ← Previous Exercise Next Exercise →🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊