Go Testing: Difference between revisions
Line 28: | Line 28: | ||
add a <code><file-name>_test.go</code> test file. In this case <code>a_test.go</code>. These files are ignored by the compiler and only compiled and executed when <code>go test</code> is run. These files will be excluded from regular package builds. | add a <code><file-name>_test.go</code> test file. In this case <code>a_test.go</code>. These files are ignored by the compiler and only compiled and executed when <code>go test</code> is run. These files will be excluded from regular package builds. | ||
The test files should be part of the same package. | The test files should be part of the same package. It is also possible to declare the test files into a corresponding package with the suffix <code>_test</code>. | ||
The test files should import <code>testing</code>. | The test files should import <code>testing</code>. |
Revision as of 22:38, 19 September 2023
External
Internal
Overview
Go comes with a lightweight test framework that includes the go test
command and the testing
package. The tests live in *_test.go
files.
Write a Unit Test
Write a module as shown here:
For each file containing behavior to test (a.go
)
package a
func Reverse(s string) string {
rs := []rune(s)
var result []rune
for i := len(rs) - 1; i >= 0; i-- {
result = append(result, rs[i])
}
return string(result)
}
add a <file-name>_test.go
test file. In this case a_test.go
. These files are ignored by the compiler and only compiled and executed when go test
is run. These files will be excluded from regular package builds.
The test files should be part of the same package. It is also possible to declare the test files into a corresponding package with the suffix _test
.
The test files should import testing
.
Add individual tests, as functions starting with TestX..
, where X...
does not start with a lowercase letter, and taking an argument t *testing.T
. The function name serves to identify the test routine. Within these functions, use Error
, Fail
or related methods to signal failure.
func TestX...(t *testing.T) {
...
t.Error("expected this: %q, got that: %q ", ...)
}
package a
import "testing"
func TestReverseEmptyString(t *testing.T) {
expected := ""
result := Reverse("")
if result != expected {
t.Errorf("expected %q, got %q", expected, result)
}
}
func TestReverseOneCharString(t *testing.T) {
expected := "a"
result := Reverse("a")
if result != expected {
t.Errorf("expected %q, got %q", expected, result)
}
}
func TestReverseTwoCharString(t *testing.T) {
expected := "ba"
result := Reverse("ab")
if result != expected {
t.Errorf("expected %q, got %q", expected, result)
}
}
From the module directory, run the tests:
go test
PASS ok example.com/a 0.116s
TO DO
- Integrate see external test packages.
- Testing idiom "Introducing Go" page 96.