Introduction to Go Testing
Start with Introduction to Go Testing
In this lesson, explore introduction to go testing through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of introduction to go testing.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Go has a built-in testing package and a go test command. Place tests in files ending with _test.go; these files compile only for tests, not normal go run.
A test should state an input, an expected result and what to report when behavior differs. Keep tests deterministic and small before layering in external dependencies.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Actual test file
Place this code in add_test.go, alongside your production add function:
package main
import "testing"
func TestAdd(t *testing.T) {
if got := add(2, 3); got != 5 { t.Fatalf("add(2,3)=%d; want 5", got) }
}From your module directory run go test ./.... See Add a test.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func add(a, b int) int { return a + b }
func main() {
got, want := add(2, 3), 5
fmt.Println("Example passes:", got == want)
}
Output
Example passes: trueTrace what the program does
The executable checks an example expectation to introduce the assertion idea. In real Go testing, move that assertion into TestAdd in add_test.go and run go test.
Avoid common mistakes
- A main.go printout is not a substitute for a test that the go test command runs.
- Tests should report failures with useful input and expected-versus-actual values.
Try it yourself
Create a TestAdd function in add_test.go with three different inputs.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Introduction to Go Testing in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.