Go/Tests
From charlesreid1
Contents
Basics
How testing works in Go
For each file X.go
a corresponding test named X_test.go
should contain unit tests for that code.
To run tests, just use the built-in test command in go: go test
Example
Example function to test
Take this simple function as an example:
package main import ( "fmt" ) // Return the square of a number func square(x int) (result int) { return x * x } func main() { fmt.Println("Hello World") }
Simple test
We can write a corresponding test:
// main_test.go package main import ( "testing" ) func test_square(t *testing.T) { if test_square(2) != 4 { t.Error("Error testing square(): did not return correct result") } }
Test matrix
We can implement a matrix of tests using a for loop:
// main_test.go package main import ( "testing" ) func test_squares(t *testing.T) { var tests = []struct { input int expected int }{ {2, 4}, {-1, 1}, {0, 0}, {-5, 25}, {1000, 1000000}, } for _, test := range tests { output := Calculate(test.input) if output != test.expected { t.Error("Test Failed: {} inputted, {} expected, received: {}", test.input, test.expected, output) } } }
Resources
Introduction to testing in Go: https://tutorialedge.net/golang/intro-testing-in-go/
Advanced Go testing tutorial: https://tutorialedge.net/golang/advanced-go-testing-tutorial/
Flags
Go notes on Go
Go/Strings · Go/Arrays · Go/Slices
Go/Lists · Go/Maps · Go/Stacks · Go/Queues
Go/Naming Conventions · Go/Design Patterns
Go/Timing · Go/Profiling · Go/Benchmarking
Go/Tests · Go/Travis CI · Go/Makefiles
our vim + go setup uses custom solarized colors for Golang
|