About
Go has a lightweight test framework composed of:
- the go test command
- and the testing package.
Example
Create a file myGoFile_test.go in the same directory that the file to test myGoFile
package main
import (
"testing"
"os"
"path/filepath"
"fmt"
)
func TestFileExist(t *testing.T) {
const temp = "TEMP"
tempDoesExist, _ := os.LookupEnv(temp);
// Exist
if _, err := os.Stat(tempDoesExist); err == nil {
// path/to/file exists
fmt.Printf("The path (%s) does exist", tempDoesExist)
} else {
t.Errorf("The path (%s) must exist", tempDoesExist)
}
// Doesn't exist
tempDoesNotExist := filepath.Join(tempDoesExist, "1Er45pt")
if _, err := os.Stat(tempDoesNotExist); os.IsNotExist(err) {
// path/to/file does not exist
fmt.Printf("The path (%s) does not exist", tempDoesNotExist)
} else {
t.Errorf("The path (%s) must not exist", tempDoesNotExist)
}
}
Setup and TearDown
To add a setup and teardown method, just add the following code.
func TestMain(m *testing.Main) {
setup()
exitCode := m.Run()
shutdown()
os.Exit(exitCode)
}