Go Tests
Go Tests are used to test Go code. They work in the following workspace types:
- Go
Test Structure
Folder Structure
Go tests execute a main_test.go file that is injected into the learner's workspace. Authors do not need to add this file.
Test File Structure
Go tests should either be defined in the same package as the learner's code, or import their code as a package. Test function names begin with Test
and take a pointer to the testing
package's testing.T
type as a parameter.
Assertions are available from the assert
package in the testify
module, which is included in the Go workspace type.
- Every assert func takes the
testing.T
object as the first argument. This is how it writes the errors out through the normal go test capabilities. - Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions.
// Assuming the learner's code is also defined in the `main` package
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestOne(t *testing.T) {
// assertions
}
func TestTwo(t *testing.T) {
// assertions
}
Example Tests
package math
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestAdd(t *testing.T) {
// assert equality
assert.Equal(t, Add(4, 6), 10, "Add(4, 6) should return 10")
}
This test assumes we have another file defining these functions, also in the math
package:
package math
// Add is our function that sums two integers
func Add(x, y int) (res int) {
return x + y
}
// Subtract subtracts two integers
func Subtract(x, y int) (res int) {
return x - y
}
Other Guidelines
- Actual code (real variable names, language syntax, etc. ) in feedback messages should be code-ticked (`)
- Go tests should follow Test standards.