Packages, modules and tooling · 3 MIN READ
Tests are a file, not a framework
Write a table-driven test and run it locally.
A test is a function such as func TestParse(t *testing.T) in a file ending _test.go. It can use the production package name, or a package name ending _test to exercise the exported API from outside the package.
A table-driven test keeps cases in data and the assertion in code. t.Run gives each case a separate name in the result stream. No external test framework is required.
SEE THE IDEA
A test is ordinary Go with a testing entry point
- 01
File
goparser_test.goIncluded by the test build
- 02
Entry
gofunc TestParse(t *testing.T)Names the behavior being tested
- 03
Cases
got.Run(name, func(t *testing.T))Reports each named case separately
Production code and test code are compiled together according to the chosen test package.
In practice
Write tables around the observable contract: normal input, boundaries and failures. Use Fatal when continuing would make the rest of the test meaningless, and Error when collecting several independent mismatches is useful. Keep test data independent so adding a case does not change another case’s state.
Watch out
Tests in package name_test exercise the exported API; tests in the same package can also inspect unexported details.
Work through the exercise
package main
// Clamp returns value limited to the range low..high.
func Clamp(value, low, high int) int {
return value
}
func main() {}Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.
Progress stays in this browser. No account needed.