Go Testing: Difference between revisions
Jump to navigation
Jump to search
Line 14: | Line 14: | ||
For each file containing behavior to test, add a <code><file-name>_test.go</code> test file. | For each file containing behavior to test, add a <code><file-name>_test.go</code> test file. | ||
For <code>a.go</code> | For each file containing the behavior to test (<code>a.go</code>): | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> |
Revision as of 02:05, 16 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, add a <file-name>_test.go
test file.
For each file containing the 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)
}
The test file should be part of the same package.
The test file should import "testing":
import "testing"
func TestReverse() {
}
TO DEPLETE
Writing a Unit Test
- Write a _test.go test file. They should belong to the same package as the tested code. These files are ignored by the compiler and only compiled and executed when go test is run.
- Import "testing"
- Tests are identified as functions starting with Test_... and taking an argument (t *testing.T).
package blue import "testing" func TestBlue(t *testing.T) { ... t.Error("expected this, got ", ...) }
Then
go test
The command will look for any tests in any of the files in the current folder and run them.
Also see external test packages.
TODO testing idiom "Introducing Go" page 96.